0

I have a project with multiple subfolders under my include folder. For instance:

include/
|-- foo/
    |-- foo_header1.h
    \-- foo_header2.h
|-- bar/
    |-- bar_header1.h
    \-- bar_header2.h
|-- root_header1.h
\-- root_header2.h
src/
|-- foo/
    |-- foo_source1.cpp
    \-- foo_source2.cpp
|-- bar/
    |-- bar_source1.cpp
    \-- bar_source2.cpp
|-- root_source1.cpp
|-- root_source2.cpp
\-- main.cpp

Curently my Makefile is:

all:
    g++ -Iinclude/ -Iinclude/foo -Iinclude/bar -o main src/*.cpp src/foo/*.cpp src/bar/*.cpp

I want a way to make that command "smarter", so I don't hardcode all the folders in my source and include directories (potentially my project will have many folders). I just want some way to specify the root header directory and make g++ find the files recursively.

Does anyone know if I can do that? Maybe using the makefile or some special flag of g++...

  • A common approach would be [defining a variable to store the include directories](https://stackoverflow.com/q/4134764/11082165). Alternatively, you could consider using a higher-level build system like [CMake](https://cmake.org/), which would let you specify the project structure more programmatically. – Brian61354270 Nov 17 '21 at 23:06

1 Answers1

2

You could just add "-Iinclude" to g++ and include the headers as following

#include <foo/foo_header1.h>
#include <bar/bar_header2.h>

This also eliminates the need to have the foo/bar prefix in the header filename. After renaming, the above simplifies to follows

#include <foo/header1.h>
#include <bar/header2.h>
  • That indeed worked, much thanks. Can you figure out some way to also make the *.cpp part better? I can create a variable with the list of directories (like `SRC_FILES=src/*.cpp src/foo/*.cpp src/bar/*.cpp ...`), but that was what I was trying to avoid in the first place. – Lucas Paiolla Nov 18 '21 at 00:22
  • 2
    @LucasPaiolla: If this solved your problem, please be certain to mark it as the accepted answer by clicking the gray checkmark next to the answer. That will mark your question as answered. – Jeremy Caney Nov 18 '21 at 00:35
  • @LucasPaiolla There isn't much for that. We generally have a make/cmake in the project root, and then more cmake files in each of the src dir. The root cmake includes all the subdirectories. The cmake in each subdirectory has to specify all the local .cpp files anyway though. – Arjun Mehta Nov 18 '21 at 09:35
  • Thanks, I think that's what I'm going to do. – Lucas Paiolla Nov 18 '21 at 14:47