g++ gives me errors of the form:
foo.cc:<line>:<column>: fatal error: <bar>: No such file or directory
compilation terminated.
It is the same when compiling C-programs with gcc.
Why is that?
Please note: This question has been asked many times before, but each time it was specific to the askers situation. This question’s purpose is to have a question that others can be closed as duplicates of, once and for all; a FAQ.
Your compiler just tried to compile the file named
foo.cc. Upon hitting line numberline, the compiler finds:or
The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file
bar. For an explanation of the difference between the versions of the include statement look here.How to tell the compiler where to find it
g++has an option-I. It lets you add include search paths to the command line. Imagine that your filebaris in a folder namedfrobnicate, relative tofoo.cc(assume you are compiling from the directory wherefoo.ccis located):You can add more include-paths; each you give is relative to the current directory. Microsoft’s compiler has a correlating option
/Ithat works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.Now imagine you have multiple version of
barin different folders, given:The priority with
#include "bar"is leftmost:As you see, when the compiler started looking through
A/,B/andC/, it stopped at the first or leftmost hit.This is true of both forms,
include <>andincude "".Difference between
#include <bar>and#include "bar"Usually, the
#include <xxx>makes it look into system folders first, the#include "xxx"makes it look into the current or custom folders first.E.g.:
Imagine you have the following files in your project folder:
with
main.cc:For this, your compiler will
#includethe filelistin your project folder, because it currently compilesmain.ccand there is that filelistin the current folder.But with
main.cc:and then
g++ main.cc, your compiler will look into the system folders first, and because<list>is a standard header, it will#includethe file namedlistthat comes with your C++ platform as part of the standard library.This is all a bit simplified, but should give you the basic idea.
Details on
<>/""-priorities and-IAccording to the gcc-documentation, the priority for
include <>is, on a “normal Unix system”, as follows:The documentation also states:
To continue our
#include<list> / #include"list"example (same code):and
and indeed, the
-I.prioritizes the folder.over the system includes and we get a compiler error.