- publishing free software manuals
An Introduction to GCC - for the GNU compilers gcc and g++
by Brian J. Gough, foreword by Richard M. Stallman
Paperback (6"x9"), 144 pages
ISBN 0954161793
RRP £12.95 ($19.95)

"Answers common questions and provides many useful hints" --- Dr. Gerald Pfeifer (SUSE) -- Technical Editor Get a printed copy>>>

4.1 Defining macros

The following program demonstrates the most common use of the C preprocessor. It uses the preprocessor conditional #ifdef to check whether a macro is defined:

#include <stdio.h>

main (void)
#ifdef TEST
  printf ("Test mode\n");
  printf ("Running...\n");
  return 0;

When the macro is defined, the preprocessor includes the corresponding code up to the closing #endif command. In this example, the macro which is tested is called TEST, and the conditional part of the source code is a printf statement which prints the message "Test mode".

The gcc option -DNAME defines a preprocessor macro NAME from the command line. If the program above is compiled with the command-line option -DTEST, the macro TEST will be defined and the resulting executable will print both messages:

$ gcc -Wall -DTEST dtest.c
$ ./a.out
Test mode

If the same program is compiled without the -D option then the "Test mode" message is omitted from the source code after preprocessing, and the final executable does not include the code for it:

$ gcc -Wall dtest.c
$ ./a.out

Macros are generally undefined, unless specified on the command line with the option -D, or in a source file (or library header file) with #define. Some macros are automatically defined by the compiler--these typically use a reserved namespace beginning with a double-underscore prefix ‘__’.

The complete set of predefined macros can be listed by running the GNU preprocessor cpp with the option -dM on an empty file:

$ cpp -dM /dev/null
#define __i386__ 1 
#define __i386 1 
#define i386 1 
#define __unix 1 
#define __unix__ 1 
#define __ELF__ 1 
#define unix 1 

Note that this list includes a small number of system-specific macros defined by gcc which do not use the double-underscore prefix. These non-standard macros can be disabled with the -ansi option of gcc.

ISBN 0954161793An Introduction to GCC - for the GNU compilers gcc and g++See the print edition