Bergwolf
Bergwolf

Reputation: 75

Expanding macros in C according to specified header files

I have a source file foo.c and a header file bar.h. How can I just expand the macros in bar.h without expanding macros in other header files?

$ cat foo.c

#include <stdio.h>
#include "bar.h"

int main()
{
#ifdef BAR_FUNC
    printf("bar func\n");
#else
    printf("foo func\n");
#endif
    return 0;
}

$ cat bar.h

#define BAR_FUNC 1

What I want is:

$ EXPAND_MAGIC foo.c

#include <stdio.h>

int main()
{
    printf("bar func\n");
    return 0;
}

If I use `gcc -E, it expands <stdio.h> as well. But I just want to expand macros in bar.h. Is there an option in gcc doing that? If not, are there any other tools that can do such preprocessing?

Update: Above foo.c/bar.h is just an example. In reality, I have a few hundreds of macros defined in bar.h (pls consider config.h generated by autoconf in a fairly large project). And what I want is to expand all (and ONLY) these macros in more than 10K source files. Any suggestions?

Upvotes: 1

Views: 2025

Answers (4)

anishsane
anishsane

Reputation: 20980

Try:
Normally compile: gcc -include stdio.h -imacros bar.h foo.c
Compile to expand ONLY MACROS in bar.h: gcc -E -imacros bar.h foo.c

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

Unfortunately for you the proeprocessos is all-or-nothing. Either you run it and it includes all requested files and expands all macros.

However you can kind of work around it by using the conditional compilation features of the preprocessor:

#ifndef INCLUDE_ONLY_BAR
# include <stdio.h>
#endif
#include "bar.h"

int main()
{
#ifdef BAR_FUNC
    printf("bar func\n");
#else
    printf("foo func\n");
#endif
    return 0;
}

You can "compile" it as such:

$ gcc -E -DINCLUDE_ONLY_BAR foo.c

Upvotes: 1

Dale Hagglund
Dale Hagglund

Reputation: 16430

You might look into the program sunifdef which is mentioned in the answer to this question. It allows you specify macro definitions on the command line, and it eliminates #ifdef lines appropriately. Note that it doesn't do macro expansion.

That said, you shouldn't use a tool like this for general development, but it's quite useful for decoding or cleaning up a code that has gotten messy with many unused #ifdefs's over the years.

Upvotes: 1

CCoder
CCoder

Reputation: 2335

You can use an IDE like eclipse. It disables the part of the code which is not compiled. You might not be able to see 'exactly' what you want to see, but you can see a clear difference between disabled code and normal code. Please ignore this option if you don't have luxury of using GUI.

Eclipse also helps in expanding macros which can be very handy when you have complex macros.

Upvotes: 0

Related Questions