user4016367
user4016367

Reputation: 481

gcc -I doesn't change the include directory

I have a folder called code/, under this folder I have a folder called include/ and the source file called code.cc, the include/ contains the header files a.h, b.h, and these two header files also exist somewhere else, in order to use the header files in the include/ folder, I added a flag -Iinclude in my Makefile, but my code still uses those header files in other places, if I include the header files in the way below, my code uses the header files under include/, why doesn't the -I flag change the include directory?

#include "include/a.h"
#include "include/b.h"

Edit: Directory:

code/code.cc
code/Makefile
code/include/a.h
code/include/b.h

Makefile:

CFLAGS = -Iinclude/
CFLAGS += -m32 
LDFLAGS = -Llib -llits -lrt -lpthread -Wl,-R,'lib'
code:code.cc
    gcc -o code $(CFLAGS) $(LDFLAGS) code.cc

gcc --version:

gcc (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973]
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 2

Views: 10882

Answers (3)

nos
nos

Reputation: 229304

With this setup:

code/code.cc
code/Makefile
code/include/a.h
code/include/b.h

And by adding -Iinclude/ to the compiler flags, your #include "include/a.h" would look for include/a.h in the include/ folder first. i.e. the compiler looks for include/include/a.h which does not exist, and the compiler looks for the include/a.h file elsewhere in the search path.

Your code either have to use #include "a.h" , or your -Iinclude/ would have to be -I. -I. adds the current directory to the search path, such that #include "include/a.h" would match the file ./include/a.h Make sure -I. is added before any other search paths that would also match your included files.

Upvotes: 2

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You have to use

CFLAGS = -I<full_path_to_project>/code

if include is placed below this directory, and you include files relative to it as in your include statement

#include "include/a.h"
      // ^^^^^^^^^

If you specify

CFLAGS = -I<full_path_to_project>/code/include

You don't need to specify relative include paths

#include "a.h"

Relative pathes specified with -I will start with the working directory used by make. If there isn't a relative path part from there, you omit the -I option, or specify -I./.

Upvotes: 0

simurg
simurg

Reputation: 1208

The order of -I directives to gcc is important. The -I directive that adds "those header files in other places" must be coming before -Iinclude for /include.

Upvotes: 0

Related Questions