views:

315

answers:

6

I am wondering how compilers on Mac OS X, Windows and Linux know where to find the C header files.

Specifically I am wondering how it knows where to find the #include with the <> brackets.

#include "/Users/Brock/Desktop/Myfile.h"    // absolute reference
#include <stdio.h>                         // system relative reference?

I assume there is a text file on the system that it consults. How does it know where to look for the headers? Is it possible to modify this file, if so where does this file reside on the operating system?

+4  A: 
Alok
+4  A: 

When the compiler is built, it knows about a few standard locations to look for header file. Some of them are independent of where the compiler is installed (such as /usr/include, /usr/local/include, etc.) and some of the are based on where the compiler is installed (which for gcc, is controlled by the --prefix option when running configure).

Locations like /usr/include are well known and 'knowledge' of that location is built into gcc. Locations like /usr/local/include is not considered completely standard and can be set when gcc is built with the --with-local-prefix option of configure.

That said, you can add new directories for where to search for include files using the compiler -I command line option. When trying to include a file, it will look in the directories specified with the -I flag before the directories I talked about in the first paragraph.

R Samuel Klatchko
+6  A: 

The OS does not know where look for these files — the compiler does (or more accurately, the preprocessor). It has a set of search paths where it knows to look for headers, much like your command shell has a set of places where it will look for programs to execute when you type in a name. The GCC documentation explains how that compiler does it and how these search paths can be changed.

Chuck
bobby
A: 

If you were using g++, you could do something like this to find out what include paths were searched:

touch empty.cpp
g++ -v empty.cpp

I don't know if there's an equivalent for Xcode. Maybe that will work since Xcode is based on GCC?

Dan
+2  A: 

In Visual Studio, it's either in the project settings if you use the IDE, or in the %INCLUDE% environment variable if you use the command line.

Alex
A: 

You should avoid #include-ing files using absolute paths. The compiler searches for the include files in various directories and includes files, starting from each directory. For example;

#include <boost/tokenizer.hpp>

Works because the boost root directory contains a folder called 'boost' and that folder is either in your default include path or you did something like.

g++ -I$BOOST_ROOT {blah,  blah}

It is C and C++ standard that the UNIX separator '/' will work the same way for all systems, regardless of what the host system actually uses to denote directories. As others of mentioned, occasionally #include doesn't actually include a real file at all.

Chris Huang-Leaver