Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I see defined macros during compilation of a C code?

I have a piece of code which compiles without problems with x86 gcc 4.4.1 but fails with blackfin gcc 4.1.2 with many "expected unqualified-id before numeric constant" errors. I see that there are some variable names that clash with some predefined macros. Is it possible to see defined macros at a certain line of a cpp file?

like image 999
Atilla Filiz Avatar asked Feb 19 '10 10:02

Atilla Filiz


People also ask

How do you check if a macro is defined in C?

Inside of a C source file, you can use the #ifdef macro to check if a macro is defined.

Can we define a macro at compile time?

You can define any macro on the compiler command line with -D. Use that to specify the model or variant you want, and based on that, #ifdefs in the code enable the other relevant macros.

Where are macros stored in C?

Macros are not stored in memory anywhere in the final program but instead the code for the macro is repeated whenever it occurs. As far as the actual compiler is concerned they don't even exist, they've been replaced by the preprocessor before they get that far.

Are there macros in C?

Macro in C programming is known as the piece of code defined with the help of the #define directive. Macros in C are very useful at multiple places to replace the piece of code with a single value of the macro. Macros have multiple types and there are some predefined macros as well.


1 Answers

gcc -dM -E myfile.cpp
  • The -dM switch tells GCC to dump all the macros defined in the given file (it will include a list of macros required to be defined by the language standard as well as any additional macros GCC defines itself).

  • The -E switch tells GCC not to continue compiling after it has preprocessed the file.

In order to see a list of macros defined at a given line of a cpp file, it may be easier to first filter out any of the predefined macros (macros defined by the compiler). In BASH, you could do:

LINE=40
FILE=myfile.cpp
HEADER=myfile.h
diff <(grep -h '#include[[:space:]]*<.*>' ${FILE} ${HEADER} | gcc -dM -x c++ -E -) <(cat ${FILE} | head -n ${LINE} | gcc -x c++ -dM -E -)

This should filter out any macros defined by standard system headers or frameworks. The extra part, -x c++, tells GCC to interpret the input as C++ source [that requires preprocessing], this is because the it won't be able to determine it based on the extension of the filename (the source code is handed to GCC via stdin).

like image 187
dreamlax Avatar answered Nov 16 '22 00:11

dreamlax