开发者

Processing some directives leaving others

I use to go through C code having lot of #ifdef, #if and #endif directive w开发者_Go百科hich keep some portion active and some portion inactive depending on some variables are defined or not. I searched for something that can process them to generate final C code. But the preprocessing also does the same for #include and #define. But I want to keep them.

So, is there any thing to preprocess these files or project with some filtering?


There are a series of programs that can do that:

  • unifdef - the oldest
  • sunifdef (Son of Unifdef)
  • coan (Son of sunifdef)

I've used sunifdef extensively on some very contorted code and have never found it to make a mistake. I'm ready to start using coan now, though it will still be under scrutiny for a while. Version 4.2.2 was released today, 2010-12-20.

See also: SO 525283


I assume you're using gcc.

If you mean all #includes, I think you need to remove them, expand the resulting file with gcc -E then add the #includess back.

If you mean only the standard headers, the option -nostdinc may help you do what you want

user@host:~/test/tmp$ cat 4437465.c
#include <stdio.h>

#ifndef OUTPUT_TYPE
#define OUTPUT_TYPE 1
#endif

int main(void) {
#if OUTPUT_TYPE == 1
  printf("output type 1\n");
#elif OUTPUT_TYPE == 2
  printf("output type 2\n");
#else
  printf("default output type\n");
#endif
  return 0;
}
user@host:~/test/tmp$ gcc -DOUTPUT_TYPE=2 -nostdinc -E 4437465.c
# 1 "4437465.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "4437465.c"
4437465.c:1:19: error: no include path in which to search for stdio.h






int main(void) {



  printf("output type 2\n");



  return 0;
}


what you want might be actually a bad idea, as there might be definitions coming from included files, describing your architecture, for example... But any modern IDE can visualize the #if preprocessor directives.


We used a custom parser to achieve what you intend to do. Lex & YACC would be a good start for such tool.

On a side note, it was a really painful way to manage different versions of binaries in a large code base. If it's possible, try to isolate your optionnal code parts in different libraries that can or cannot be included in your final deliverable as a dynamic or static library.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜