Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see the actual order of include files after preprocessing?

I have one .cpp file that includes a few header files. These header files may include other header files as well. Include guards are in place to prevent including the same file twice.

Knowing that each file is only included once. Is there a way to figure out the eventual order in which all headers will be included?

I tried gcc -E to get the preprocessor output, but the generated code doesn't seem usable for extracting the information that I want. Can anyone help?

Edit

The reason why I'm asking is because I need to include my header files in a SWIG interface file in the correct order to avoid generation of weird SWIGTYPE_p_* wrappers.

Update

Thanks for the answers. Using cpp -H seems very useful. However, I can't find way to grep or sed these results in order to get the simple list of header files in the correct order and without duplicates.

like image 488
StackedCrooked Avatar asked Mar 10 '11 11:03

StackedCrooked


2 Answers

Use cpp -H. This prints the headers used to standard error. Example:

$ cpp -H -I../../include base64.cpp 2>&1 >/dev/null | head
. /usr/include/c++/4.4/cstring
.. /usr/include/c++/4.4/i486-linux-gnu/bits/c++config.h
... /usr/include/c++/4.4/i486-linux-gnu/bits/os_defines.h
.... /usr/include/features.h
..... /usr/include/bits/predefs.h
..... /usr/include/sys/cdefs.h
...... /usr/include/bits/wordsize.h
..... /usr/include/gnu/stubs.h
...... /usr/include/bits/wordsize.h
...... /usr/include/gnu/stubs-32.h

See the GNU cpp manual for details.

EDIT Here's a small Python script that will show the order of inclusion, assuming all headers have include guards:

import sys
seen = set()
for ln in sys.stdin:
    dots, header = ln.rstrip().split(' ', 1)
    if x not in seen:
        seen.add(header)
        print header

(You should be able to translate this to Awk or Perl if Python is not your cup of tea.)

like image 102
Fred Foo Avatar answered Nov 09 '22 06:11

Fred Foo


The preprocessor works sequentially, you can "easily" follow his job by hand.

say you have :

file.cpp

#include 'one.h'
#include 'two.h'

one.h

#include 'three.h'
#include 'header.h'

three.h

#include 'four.h'

The preprocessor will include one.h, which will include three.h which will include four.h. Now we return to one.h and header.h will be included and finally we return to file.cpp and two.h will be included. So the order will be

  1. one.h
  2. three.h
  3. four.h
  4. header.h
  5. two.h

I don't know why you're asking this, but I strongly suggest you write your headers in a way that any kind of non-deterministic inclusion order work, otherwise you'll run in some problems sooner or later.

like image 5
krtek Avatar answered Nov 09 '22 05:11

krtek