GCC Default Search Directories

Wondering (again) where gcc searches for includes when no -I include options are specified on the command line.

echo | gcc -Wp,-v -xc++ - -fsyntax-only

What we really want is some verbose output from the C++ preprocessor which we could get with `-Wp,-v` when compiling some source code. But we don’t want to have to specify some source file just to get this info, so we can use a dummy or empty file.

First thing, we’re going to compile an input file from stdin. To do this, you would just do:

gcc -

But since gcc can compile for multiple languages and relies on file extensions to select which one to use AND we aren’t going to give it an extension since the file is coming from stdin, you have to explicitly specify the language with -x <language>. So we have:

gcc -xc++ -

Now running this will result in the gcc waiting for source code text from stdin, and will keep reading till it encounters and End of File character (which you can produce with Ctrl-D). So we can either type something in, which we don’t need, or send something empty. To send some empty, we can just echo nothing and pipe it as stdin to the above gcc command. So we have:

echo | gcc -xc++ -

Since we’ve provided an empty source file, it does not find a main function, so there is an error from the linker: ‘undefined reference to main‘.

We now would like information about the preprocessor and which directories it’s using to compile our empty file. To do this, we add an option to specify a preprocessor option: -Wp,<option> and the option we want is the -v verbose option. So we now have:

echo | gcc -Wp,-v -xc++ -

This pretty much gives us what we want, but there is some extra stuff at the end. There are probably multiple ways to clean this up, but one way people suggest is to use the `-fsyntax-only` option which according to the documentation will “Check the code for syntax errors, but don’t do anything beyond that.” (gcc man page)

Which gives our final command:

echo | gcc -Wp,-v -xc++ - -fsyntax-only

Doing so outputs this on my system:

$ echo | gcc -Wp,-v -xc++ - -fsyntax-only
ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/7"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed"
ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/7/../../../../x86_64-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
End of search list.

So here it is: we see that when using double-quotes, the preprocessor has no specified search path for include files, meaning it looks in the current directory. When using angle brackets (e.g. greater-than, less-than signs), it searches in the specified order.

The next question is, how does the preprocessor get this list of search paths in the first place?

To be continued…




Leave a Reply

Your email address will not be published. Required fields are marked *