user3677630 user3677630 - 3 years ago 116
Linux Question

g++ generate dependency file miss user defined headers

The structure of the folder of my source code is defined as follows:

src
|--c
|--c.h
|--c.cpp


'c.h' declares a class called 'B' and 'c.cpp' defined the class 'B'.

Suppose we are in folder 'src' now. I run

g++ -I./ -MM -MT c/c.o -MF c/c.d c/c.cpp


to generate the dependency file 'c/c.d' for 'c/c.cpp'. The content of the file 'c/c.d', however, does not contain 'c/c.h' even if I have included 'c/c.h' in 'c/c.cpp' by

#include "c/c.h".


However, the result is different if we are in folder 'c' and run the above command. By replacing 'c/c.h' with 'c.h' in the above process, I can get a correct dependency file (meaning that 'c.h' is in the dependency file).

Anyone knows the reason of why the first process misses the header dependency?

Answer Source

According to this GCC webpage, the

"preprocessor looks for header files included by the quote form of the directive #include "file" first relative to the directory of the current file, and then in a preconfigured list of standard system directories."

That means when it sees #include "c/c.h", it checks for files in a hypothetical subdirectory named "c" from the current file's location.

When you replaced that with #include "c.h", the preprocessor then checks the directory of the current file.

Another option is to add -I../ to the command line parameters for g++.

This GCC webpage provides the complete order in which the preprocessor searches directories for include files. The lookup order is as follows:

  1. For the quote form of the include directive, the directory of the current file is searched first.
  2. For the quote form of the include directive, the directories specified by -iquote options are searched in left-to-right order, as they appear on the command line.
  3. Directories specified with -I options are scanned in left-to-right order.
  4. Directories specified with -isystem options are scanned in left-to-right order.
  5. Standard system directories are scanned.
  6. Directories specified with -idirafter options are scanned in left-to-right order.

Note that the directory from which you ran g++ does not appear on the above list. This means, the preprocessor does not check the directory from which you ran g++ on the command line. The reason is so that you can run g++ from any directory and still get the same build results.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download