Print Predefined Macros using gcc or g++ Compiler

Print Predefined Macros using gcc or g++ Compiler

When working with C or C++ code, it can be helpful to know what macros (via #define) the gcc or g++ compiler defines automatically. These predefined macros give you insight into things like the target platform, compiler version, architecture, and more. This tutorial demonstrates how to print predefined macros using gcc or g++ compiler.

Predefined macros are constants or flags automatically available in the code, defined by the compiler itself. For example, __GNUC__, __cplusplus, etc.

To list all predefined macros, we can use the -dM and -E options of gcc or g++ compiler:

gcc -dM -E - < /dev/null
g++ -dM -E -x c++ - < /dev/null
  • -dM - tells the compiler to dump all macros after preprocessing.
  • -E - run only the preprocessor stage (no compilation or linking).
  • - - the hyphen here means "read from standard input" (stdin) instead of a file. This is used in combination with the next part.
  • < /dev/null - this redirects an empty file as input, so the compiler reads no actual code, just an empty stream. We're only interested in the compiler's default macros, not user code.
  • -x c++ - explicitly tells the compiler to treat the input as C++ code. This is important since we're not using a .cpp file, and the compiler can't guess the language otherwise.

If you want to save the output to a file, you can redirect the output like this:

gcc -dM -E -o macro.txt - < /dev/null
g++ -dM -E -x c++ -o macro.txt - < /dev/null

This creates a macro.txt file containing all the predefined macros.

Leave a Comment

Cancel reply

Your email address will not be published.