Jacobi John Jacobi John - 16 days ago 5
C++ Question

Source code layouts in C++

I'm new to C++, background in Java and Python, source code file layouts in those language are pretty standard. However I've noticed with C++ projects, there seem to be at least 3 different types of layout:

Option 1 All files (.hpp and .cpp) in the same directory

---+ project
|
+-- header1.hpp
+-- header2.hpp
+-- code1.cpp
+-- code2.cpp


Option 2 Headers (.h .hpp) all in a single include directory and implementations (.cpp) in a src directory

---+ project
|
+-- include
| +-- header1.hpp
| +-- header2.hpp
|
+-- src
+-- code1.cpp
+-- code2.cpp


Option 3 Headers (.h .hpp) all in a single include directory with specific directories for different groups of headers (details, impl), all implementations (.cpp) in a single dir

---+ project
|
+-- include
| +-- header1.hpp
| +-- header2.hpp
| +-- module1
| | +-- mod1.hpp
| +-- module2
| +-- mod2.hpp
|
+-- src
+-- code1.cpp
+-- code2.cpp
+-- mod1.cpp
+-- mod2.cpp


Option 4 Similar to 3 but the implementations also have their down directories.

---+ project
|
+-- include
| +-- header1.hpp
| +-- header2.hpp
| +-- module1
| +-- mod1.hpp
| +-- module2
| +-- mod2.hpp
|
+-- src
| +-- code1.cpp
| +-- code2.cpp
| +-- module1
| | +-- mod1.cpp
| +-- module2
| +-- mod2.cpp


I've had a quick read of the standard and can't seem to find any suggestions or guidance on the matter, the same goes from cppref documentation.

Is there some common layout? or is it a situation of: "what works for you"

Answer

It really just depends on how large the project is, and whether or not you want it used as a library. If it is a library you would definitely split the headers out. For a normal executable project I normally start off just lumping everything in one directory and running g++ to compile the lot, as the project grows and you add a makefile and what not you start adding directories to keep it tidy. In most really large projects I would expect #4. But for really small projects, #1, and that is if they even bother to split the header out of implementation.

Comments