I am currently working on a C++ project with a source file structure like this (headers excluded):
src/
├── namespace1/
│ ├── namespace1_base.cpp
│ ├── namespace1_derived1.cpp
│ └── namespace1_derived2.cpp
├── namespace2/
│ ├── namespace2_base.cpp
│ ├── namespace2_derived3.cpp
│ └── namespace2_derived4.cpp
├── other.cpp
└── files.cpp
The only annoying thing using this convention is including the files because I need to use
#include "src/namespace1/namespace1_derived1.cpp"
It seems weird and unnecessary to type the namespace twice. Is it considered good practice or should I organize my source files differently?
1 Answer 1
As far as C++ the language is concerned, duplicate file names are no problem at all. A tangential problem is that of include guards which must indeed be unique per translation unit, so using a filename as the header include guard's macro's name is not sufficient. However, using the nonstandard yet widely supported #pragma once
directive completely sidesteps that problem.
But if other tools cannot deal with duplicate filenames in a project, and you have to use those tools, then you will have to live with that restriction. For example, a broken build system might want to compile both foo/myclass.cpp
and bar/myclass.cpp
to a build/myclass.o
file. Ideally the build system can be configured to avoid that problem (e.g. by building each namespace as a separate project), and if not then prefixing your filenames as in your question is an ugly but acceptable solution.
__init__.py
in each folder of a Python project, orpackage.scala
in multiple places in Scala), so that is something an IDE should support. As long as you're using namespaces, you should have no issues with the imports, even when the names are the same.