1

Suppose I have two directory product and test.

./test
./test/test_product.cpp
./test/foo.h
./product
./product/product.cpp
./product/product.h
./product/foo.h

And product.cpp include foo.h as:

#include "foo.h"

The default behavior is to include /product/foo.h. However, I want to include /test/foo.h in /product/product.cpp without any modification in product directory. Is there any way to do that? Thanks a lot!

cartman
  • 732
  • 2
  • 8
  • 20

4 Answers4

4

You can add search paths that the GCC preprocessor use to look for header files with the -I option, and then you could use angle-brackets when including the file, then the preprocessor should look for files in the same directory as the source file last.

In other words add e.g. -Itest to add the test directory to the include file search path. Then use #include <foo.h> instead. And when you want to use product/foo.h instead, just remove the -Itest option and add -Iproduct instead.


There is also another way, that involved conditional compilation and the solution suggested by Lanting.

You could have e.g.

#ifdef TEST
# include "../test/foo.h"
#else
# include "foo.h"
#endif

Then to build with test/foo.h you defined the macro TEST, which can be done on the command line using the -D option:

$ gcc -DTEST ...

To use the product/foo.h just remove the option so TEST is no longer defined.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks for answer it! Unfortunately, I cannot have any modification on product source code. So Is there any other way I can do? – cartman Mar 21 '16 at 10:36
  • 1
    @walker the method provided in http://stackoverflow.com/a/3164874/2422450 doesn't modify the source (but involves some rather complicated messing with precompiled headers) – Lanting Mar 21 '16 at 12:41
0

You're free to add full and relative paths to headers in includes.

#include "../test/foo.h"

would, for instance, work

Have a look at these discussions on how and when to use which include form: What are the benefits of a relative path such as "../include/header.h" for a header? and How to use #include directive correctly?

Community
  • 1
  • 1
Lanting
  • 3,060
  • 12
  • 28
0

You can include headers in the file by providing its path under #include. ex. #include "path to .h file"

Manish
  • 33
  • 1
  • 8
0

you can use the header guard to archive that, assuming that both files are having different header guard, you can add -D(header guard of whichever file you do not want) in the list of flags in the make file.

Nadeem Khan
  • 364
  • 3
  • 10