Processing some directives leaving others

I use to go through C code that contains many #ifdef , #if and #endif directives that keep some part active and some inactive depending on some variables whether or not they are defined. I was looking for something that could process them to generate the final C code. But preprocessing also does the same for #include and #define . But I want to save them.

So, is there any thing to pre-process these files or a project with some filtering?

+7
source share
4 answers

There are a number of programs that can do this:

I used sunifdef extensively on some very garbled code and never found that it made a mistake. Now I am ready to start using the koyo, although it will still be under close scrutiny. Version 4.2.2 was released today, 2010-12-20.

See also: SO 525283

+2
source

I assume you are using gcc.

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

If you mean only standard headers, the -nostdinc option can 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;
 } 
0
source

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

0
source

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

On the side of the note, it was a very painful way to manage different versions of binaries in a large code base. If possible, try isolating your parts of the optional code in different libraries that may or may not be included in your final result as a dynamic or static library.

0
source

All Articles