Shai Zarzewski
Shai Zarzewski

Reputation: 1698

C++ makefile with relative include path to parent

I've got a working project that I need to take parts from it without changing it's code and just write new main() for it. My directory structure:

[main_dir]/[main.cpp]

[main_dir]/[dir1]/[child1]/file1.h

[main_dir]/[dir2]/[child2]/file2.h

in main.cpp I have: include "dir1/child1/file1.h"

In file1.h I have: include "dir2/child2/file2.h"

I'm compiling: g++ main main.cpp

I'm getting "dir2/child2/file2.h" no such file or directory. I can't change file1 to do: include "../../dir2/child2/file2.h"

Somehow in the original project something in the makefile to search for all include path relative to the [main_dir] so the include from file1.h can be found.

What should I add to the makefile in order to do it as well?

Upvotes: 1

Views: 659

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

When using double-quotes to include a header file, as in

#include "dir2/child2/file2.h"

then the compiler will use the directory of the current file to search for the header file.

If you have it in your file1.h then the compiler will look for the header file [main_dir]/dir1/child1/dir2/child2/file2.h. Which isn't correct.

You can solve it by telling the compiler to add [main_dir] to the list of standard include search paths. This is done with the -I (upper-case i) option:

g++ -I [main_dir] main.cpp

Then when the compiler fails to find dir2/child2/file2.h in its first search, it will continue with the list of standard include search paths, and it should be found.

Upvotes: 2

Maneevao
Maneevao

Reputation: 361

You need to manage CPPFLAGS in your Makefile.

CPPFLAGS="-I[main_dir]"

And compile application with receipt like this:

g++ $(CPPFLAGS) main.cpp -o main

Also it's recommended to read make style guides to write a good one Makefile. You can meet there tips for include folders declaration.

Upvotes: 2

Related Questions