Reputation: 1546
When using gcc
with the -I
option, what is the priority of directories to be searched? What if your header's name conflicts with that of a system header, but they are in different directories? Which one will be #include
-ed? Also, what order are the system headers included in?
Upvotes: 1
Views: 1129
Reputation: 754280
That's a moderately complex question, and depends on whether you wrote #include <header.h>
or #include "header.h"
and on whether the file being included is included direct from your source or is included by another header.
Generally, the names in double quotes look in the directory which holds the source file for the header, then in the same places as are searched for names in angle brackets (so #include "header.h"
looks in more places than #include <header.h>
does).
You can add more places that are searched with the -I /some/other/include
command line option. These are searched in order and before the system (default) locations. The system locations that are searched can vary by platform. On Unix, it often includes /usr/local/include
and always ends with /usr/include
; it could include other places too.
If the #include
line is in another header, GCC starts the search for that nested header in the directory where the first header was found, rather than restarting at the beginning.
For some system headers on some platforms, GCC creates a secondary fixed copy of the header which it uses in place of the header in /usr/include
or its nether regions.
You can override most of these behaviours with command line options. For the full gory details, read the GCC [Preprocessor] manual on how it handles Header Files. The GCC compiler manual outlines the options that control it in the Preprocessor Options part of the manual. The preprocessor manual lists esoteric options in Invocation.
Demonstrating that 'current directory' is 'directory containing source file'.
$ mkdir x3
$ echo 'Code from x3/header1.h' > x3/header1.h
$ echo '#include "header1.h"' > x3/source.c
$ echo 'This is from the current directory, not from the subdirectory.' > header1.h
$ cpp x3/source.c
# 1 "x3/source.c"
# 1 "<command-line>"
# 1 "x3/source.c"
# 1 "x3/header1.h" 1
Code from x3/header1.h
# 1 "x3/source.c" 2
$ cpp -I . x3/source.c
# 1 "x3/source.c"
# 1 "<command-line>"
# 1 "x3/source.c"
# 1 "x3/header1.h" 1
Code from x3/header1.h
# 1 "x3/source.c" 2
$ rm x3/header1.h
$ cpp x3/source.c
# 1 "x3/source.c"
# 1 "<command-line>"
# 1 "x3/source.c"
x3/source.c:1:21: fatal error: header1.h: No such file or directory
#include "header1.h"
^
compilation terminated.
$ cpp -I . x3/source.c
# 1 "x3/source.c"
# 1 "<command-line>"
# 1 "x3/source.c"
# 1 "./header1.h" 1
This is from the current directory, not from the subdirectory.
# 1 "x3/source.c" 2
$ rm -fr header1.h x3
$
Tested with cpp
from GCC 4.8.2 on Mac OS X 10.9.2.
Upvotes: 3
Reputation: 60017
Sequential order. The first one that the files appears.
Just like the PATH
variable
Upvotes: 0