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?
Best Answer
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
andbar/myclass.cpp
to abuild/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.