Search code examples
c++compilationcode-organization

How to compile C++ files organized in a directory structure?


I've written a bunch of code now, and sorted it in a fashion similar to this outline:

project/
+ include/
| + bar/
| |   bar.hpp
|   foo.hpp
+ src/
| + bar/
| |   bar.cpp
|   foo.cpp
|   main.cpp

My question is, how do I call g++ now, so that it links everything together nicely?

I've already figured out that I need to call it with the -I option pointing to the include/ directory. I'm guessing it would make most sense calling g++ from the project/ folder. Also, I'm considering writing a Makefile to automate this process, but I have to admit I haven't done very much research on that yet.


Solution

  • I would recommend using some kind of build tool like CMake or Autotools. Creating your own Makefiles can be kind of a PITA to get right.

    If you have a small directory structure with some C++ files which you want to quickly compile, you can do something like this:

    find src/ -name "*.cpp" | xargs g++ -I include/