How to obtain files included in C++ compilation

Get all headers included by an executable in C++

Assume that the compilation of an executable is done via

cd <EXEFOLDERs> && <CPPCOMPILER> -<ALL_KINDS_OF_FLAGS> <EXECUTABLE_NAME>

where ‘CPPCOMPILER’ is either ‘clang++’ or ‘g++’ (the flags used in this article work with these two compilers, but other compilers may define similar ones).

Then, all header files included upon the compilation of ‘EXECUTABLE_NAME’ can be printed by simply adding the -H option (see linux.die.net/man/1/g++) to the compilation command. That is, for instance with g++:

cd <TARGETFOLDER> && g++ -<ALL_KINDS_OF_FLAGS> -H <TARGET>

If you want to write the included headers into a file instead, you can use the -MF option. Moreover, you may also only be interested in headers from your project. To this end, you can use the -MM option such that system headers are not considered.
Thus, the final command to write these headers into a file named deps_file looks like this:

cd <TARGETFOLDER> && g++ -<ALL_KINDS_OF_FLAGS> <TARGET> -MM -MF <deps_file>

Retrieve the compile command

If you are using a build tool like cmake or some Integrated Development Environment (IDE) for the configuration of your project, you probably don’t exactly know what the compile command looks like. In case that your configuration yields GNU Makefiles, you can find out the command by typing

make -B --dry-run <EXECUTABLE>

into the terminal from within your configured project environment. The -B option is necessary to print the full command even though a prior compilation had taken place.

See also