Hunting the wily #if

Since a reader (djmott) found some use for Stupid gcc trick #2: finding all included files, recursively
…  here’s another quick trick for finding which set of nested #ifdef/#elif/… controls the inclusion/exclusion of some piece of your source file. This perl snippet prefixes each line of a source file with an indicator of which #if/#elif/#else (lines) decided inclusion of the line of interest. Here’s part of “ifdent plat.h | nl “:

 1 +1:#ifndef PLAT_H
...
142 +1+142:#ifdef _MSC_VER
...
177 +1+142+177:# if !defined(getpid)
178 +1+142+177:# define getpid _getpid
179 +1+142:# endif
...
225 +1-142:#else
...
325 +1-142+325:# if !defined(BYTE_ORDER)
326 +1-142+325+326:# if defined(__hpux) || defined(__powerpc) || defined(__sparc)
327 +1-142+325+326:# define BYTE_ORDER BIG_ENDIAN
...
331 +1-142+325+330:# include <endian.h>
332 +1-142+325-330:# else
333 +1-142+325-330:# error BYTE_ORDER not defined
...
366 +1-142+366:# if defined(__darwin)
...
375 +1-142+366+375:# if defined(__x86_64)
376 +1-142+366+375:uint64_t bswap_64(uint64_t x) { asm("bswap %0": "=r"(x):"0"(x)); return x; }
377 +1-142+366-375:# else // i386
378 +1-142+366-375:uint64_t bswap_64(uint64_t n)
...
413 +1-142:# endif
...
1213 :#endif//PLAT_H

And the source for ifdent:

#!/usr/bin/perl -w
use strict;
my $prefix = '';
while (<>) {
    if (m{^#\s*if}) { $prefix .= "+$."; }
    elsif (m{^#\s*elif}) { $prefix =~ s{\d+$}{$.}; }
    elsif (m{^#\s*else}) { $prefix =~ s{\+(\d+)$}{-$1}; }
    elsif (m{^#\s*endif}) { $prefix =~ s{.\d+$}{}; }
    print "$prefix:$_";
}

 

 

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 https://mischasan.wordpress.com 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. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s