musteresel's blog


A regex to find C/C++ preprocessor includes

2019-10-10

tagged: c, c++

Yes I know .. “parsing” C or C++ with regular expressions is bad. There’s of course libclang (1, 2) and also some way to hook into GCC … but sometimes it’s just easier to slap a regex on the problem. In this case getting the names of the directly included files:

grep -oP '#[[:blank:]]*include[[:blank:]]*("|<)\K[\w.\/]+(?=("|>))' FILE

This calls grep with “Perl-compatible” regex support (-P) and prints only the matches (-o). The regex:

I’ve found this regex to work well in practice, though of course it may return false positives due to:

And of course it doesn’t care about conditional compilation … so this will yield foo:

#if 0
#include "foo"
#endif

But that’s exactly what I need in my case.