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?
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.
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.
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.)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With