问题
I'm using a complicated C code that includes many, many compilation options. This makes the code very hard to read. I'd like to produce a copy of the code reflecting the way it's actually compiled. I've gotten pretty good results using the "unifdef" utility, which I didn't know about until recently. However, I'm puzzled why it's so hard to invoke, and am wondering if I'm missing something.
Consider this example:
#ifdef A
printf("A\n");
#endif
#ifdef B
printf("B\n");
#endif
If you invoke unifdef with "unifdef -DA junk.c", you get:
printf("A\n");
#ifdef B
printf("B\n");
#endif
Because you didn't tell unifdef that B was undefined, it didn't take it out.
I would like the utility to behave such that when I say unifdef -DA, I get instead:
printf("A\n");
This would correspond to what the C preprocessor is actually doing: whatever branches are undefined are omitted.
To get this behavior with unifdef, I seem to need to use "unifdef -DA -UB junk.c", explicitly telling it that B is undefined. Though maybe I missed a simpler way to invoke it.
I wrote a python script to generate the long list of required -D and -U flags from the Makefile of the code I'm using (typically 80 per routine). And the results are excellent. But I'm wondering whether such a script is actually necessary.
It's also possible that another utility (sunifdef? coan?) has my desired behavior built in already; if so, please mention it.
回答1:
The coan utility does what you need with the -m
flag:
$ coan source -DA -m test.c
printf("A\n");
From the man page:
-m, --implicit
Assume that any symbol that is not --define-ed is implicitly
--undef-ed.
回答2:
You can use the unifdefall utility which comes with unifdef. See http://dotat.at/prog/unifdef
回答3:
If I understood your question correctly, you want to see the code after the pre-processor has ran over it, correct? Then why don't you let the pre-processor run over it and look what output it produces? Just run the compile call using exactly the same arguments you would use when compiling, but add the argument -E
to it, which means "Do nothing but pre-processing".
$ cat preproc.c
#ifdef A
printf("A\n");
#endif
#ifdef B
printf("B\n");
#endif
$ gcc -E preproc.c
# 1 "preproc.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "preproc.c"
$ gcc -E -DA preproc.c
# 1 "preproc.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "preproc.c"
printf("A\n");
$ gcc -E -DB preproc.c
# 1 "preproc.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "preproc.c"
printf("B\n");
$
来源:https://stackoverflow.com/questions/14491555/way-to-omit-undefined-preprocessor-branches-by-default-with-unifdef