Stupid gcc trick #2: finding all included files, recursively

“C” programmers live in a love-hate relationship with #include files. They make it possible to import and ignore details of implementation; but sometimes, you really want to know about the implementation.

For example, suppose you want to find the definition of a #define‘d constant, precisely. Your own program #include‘s <stdio.h>, <sys/types.h> etc. … but grepping those files doesn’t find what you want. What you really would like is to know all the files included, recursively.

Here again gcc comes to the rescue. gcc -M produces make-style dependencies, which are pretty close to what we want:

$ echo >foo.h '#include <time.h>'
$ echo >foo.c '#include "foo.h"
int main(void) { return 0; }'
$ gcc -M foo.c
foo.o: foo.c foo.h /usr/include/time.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/gnu/stubs-32.h \
 /usr/lib/gcc/i486-linux-gnu/4.4.5/include/stddef.h \
 /usr/include/bits/time.h /usr/include/bits/types.h \
 /usr/include/bits/typesizes.h /usr/include/xlocale.h

That’s close to what we want. Now, a little tweak to get a simple list of files:

$ ls -1 2>&- `gcc -M foo.c`

ls 2>&-” silently removes the “foo.o:” and backslashes, sorts and and prints one file per line.


About mischasan

I've had the privilege to work in a field where abstract thinking has concrete value. That applies at the macro level --- optimizing actions on terabyte database --- or the micro level --- fast parallel string searches in memory. You can find my documents on production-system radix sort (NOT just for academics!) and some neat little tricks for developers, on my blog My e-mail sig (since 1976): Engineers think equations approximate reality. Physicists think reality approximates the equations. Mathematicians never make the connection.
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

2 Responses to Stupid gcc trick #2: finding all included files, recursively

  1. Pingback: Stupid gcc trick #3: list all built-in gcc #define symbols | Coding on the edges

  2. Pingback: The “C” preprocessor: not as cryptic as you’d think | Coding on the edges

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s