Gulshan
Gulshan

Reputation: 3761

Processing some directives leaving others

I use to go through C code having lot of #ifdef, #if and #endif directive which 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?

Upvotes: 7

Views: 224

Answers (4)

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

There are a series of programs that can do that:

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

Upvotes: 2

Matthieu
Matthieu

Reputation: 4620

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.

Upvotes: 0

kódfodrász
kódfodrász

Reputation: 121

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.

Upvotes: 0

pmg
pmg

Reputation: 108988

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;
}

Upvotes: 0

Related Questions