8

I'm attempting to refactor a piece of legacy code and I'd like a snapshot of all of the macros defined at a certain point in the source. The code imports a ridiculous number of headers etc. and it's a bit tedious to track them down by hand.

Something like

#define FOO 1


int myFunc(...) {
    PRINT_ALL_DEFINED_THINGS(stderr)

    /* ... */
}

Expected somewhere in the output

MACRO: "FOO" value 1

I'm using gcc but have access to other compilers if they are easier to accomplish this task.

EDIT:

The linked question does not give me the correct output for this:

#include <stdio.h>

#define FOO 1

int main(void) {
    printf("%d\n", FOO);
}

#define FOO 0

This very clearly prints 1 when run, but gcc test.c -E -dM | grep FOO gives me 0

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
  • you can do it from the compiler. i did it the other day. h/o i'll look for what i did – Steve Cox Jun 24 '14 at 14:03
  • As far as I know, such a thing does neither exist nor is it easily achievable as macros are evaluated before the C compiler compiles. – usr1234567 Jun 24 '14 at 14:03
  • @SteveCox Works with things you `#define` yourself as well. I even tested before closing as duplicate. – Lundin Jun 24 '14 at 14:06
  • @Lundin yeah sorry, the question was just for predefined as a read it, but the answer was more general – Steve Cox Jun 24 '14 at 14:06
  • Perhaps you could run cpp (C preprocessor) and get a macro-expanded copy of the program, and compare it to the original source to see the differences (e.g., using WinMerge or diff). Still a tedious and error-prone way, especially if big chunks of C code are being included. – Phil Perry Jun 24 '14 at 14:07
  • gcc -E filename.c will generate the pre-processor out. – mahendiran.b Jun 24 '14 at 14:16
  • Could you take the output from the -dM option and via sed scripts convert all the #define symbols into printfs with %s and stringify "#" the value of the macro. Pipe the code generated by this script into a header file that you could #include inline in at the location you wanted, or pipe it into a header file in the form of a macro that you could invoke as needed. Its feels like an awful hack but might come close? – dennis Jun 24 '14 at 21:20

1 Answers1

6

To dump all defines you can run:

gcc -dM -E file.c

Check GCC dump preprocessor defines

All defines that it will dump will be the value defined (or last redefined), you won't be able to dump the define value in all those portions of code.

You can also append the option "-Wunused-macro" to warn when macros have been redefined.

Community
  • 1
  • 1
denisvm
  • 720
  • 3
  • 11