This is part of the GNU C Intro and Reference Manual and covered by its license.

Preprocessing
*************

As the first stage of compiling a C source module, GCC transforms the text with text substitutions and file inclusions.  This is called preprocessing.

Preprocessing Overview
======================

GNU C performs preprocessing on each line of a C program as the first stage of compilation.  Preprocessing operates on a line only when it contains a preprocessing directive or uses a macro---all other lines pass through preprocessing unchanged.

Here are some jobs that preprocessing does.  The rest of this chapter gives the details.

  * Inclusion of header files.  These are files (usually containing declarations and macro definitions) that can be substituted into your program.

  * Macro expansion.  You can define macros, which are abbreviations for arbitrary fragments of C code.  Preprocessing replaces the macros with their definitions.  Some macros are automatically predefined.

  * Conditional compilation.  You can include or exclude parts of the program according to various conditions.

  * Line control.  If you use a program to combine or rearrange source files into an intermediate file that is then compiled, you can use line control to inform the compiler where each source line originally came from.

  * Compilation control.  #pragma and _Pragma invoke some special compiler features in how to handle certain constructs.

  * Diagnostics.  You can detect problems at compile time and issue errors or warnings.

Except for expansion of predefined macros, all these operations happen only if you use preprocessing directives to request them.

Directives
==========

Preprocessing directives are lines in the program that start with #.  Whitespace is allowed before and after the #. The # is followed by an identifier, the directive name. It specifies the operation to perform.  Here are a couple of examples:

     #define LIMIT 51
       #   undef LIMIT
     # error You screwed up!

We usually refer to a directive as #NAME where NAME is the directive name.  For example, #define means the directive that defines a macro.

The # that begins a directive cannot come from a macro expansion.  Also, the directive name is not macro expanded.  Thus, if foo is defined as a macro expanding to define, that does not make #foo a valid preprocessing directive.

The set of valid directive names is fixed.  Programs cannot define new preprocessing directives.

Some directives require arguments; these make up the rest of the directive line and must be separated from the directive name by whitespace.  For example, #define must be followed by a macro name and the intended expansion of the macro.

A preprocessing directive cannot cover more than one line.  The line can, however, be continued with backslash-newline, or by a /*...*/-style comment that extends past the end of the line.  These will be replaced (by nothing, or by whitespace) before the directive is processed.

Preprocessing Tokens
====================

Preprocessing divides C code (minus its comments) into tokens that are similar to C tokens, but not exactly the same. Here are the quirks of preprocessing tokens.

The main classes of preprocessing tokens are identifiers, preprocessing numbers, string constants, character constants, and punctuators; there are a few others too.

identifier
     An identifier preprocessing token is syntactically like an identifier in C: any sequence of letters, digits, or underscores, as well as non-ASCII characters represented using \U or \u, that doesn't begin with a digit.

     During preprocessing, the keywords of C have no special significance; at that stage, they are simply identifiers.  Thus, you can define a macro whose name is a keyword.  The only identifier that is special during preprocessing is defined (see defined).

preprocessing number
     A preprocessing number is something that preprocessing treats textually as a number, including C numeric constants, and other sequences of characters which resemble numeric constants. Preprocessing does not try to verify that a preprocessing number is a valid number in C, and indeed it need not be one.

     More precisely, preprocessing numbers begin with an optional period, a required decimal digit, and then continue with any sequence of letters, digits, underscores, periods, and exponents.  Exponents are the two-character sequences e+, e-, E+, E-, p+, p-, P+, and P-.  (The exponents that begin with p or P are new to C99.  They are used for hexadecimal floating-point constants.)

     The reason behind this unusual syntactic class is that the full complexity of numeric constants is irrelevant during preprocessing. The distinction between lexically valid and invalid floating-point numbers, for example, doesn't matter at this stage.  The use of preprocessing numbers makes it possible to split an identifier at any position and get exactly two tokens, and reliably paste them together using the ## operator (see Concatenation).

punctuator
     A punctuator is syntactically like an operator. These are the valid punctuators:

          [  ]   (  )  {  }  .  ->
          ++ --  &  *  +  -  ~  !
          /  %   << >> <  >  <= >=  ==  !=  ^  |  &&  ||
          ?  :   ;  ...
          =  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |=
          ,  #   ##
          <: :>  <% %>  %:  %:%:

string constant
     A string constant in the source code is recognized by preprocessing as a single preprocessing token.

character constant
     A character constant in the source code is recognized by preprocessing as a single preprocessing token.

header name
     Within the #include directive, preprocessing recognizes a header name token.  It consists of "NAME", where NAME is a sequence of source characters other than newline and ", or <NAME>, where NAME is a sequence of source characters other than newline and >.

     In practice, it is more convenient to think that the #include line is exempt from tokenization.

other
     Any other character that's valid in a C source program is treated as a separate preprocessing token.

Once the program is broken into preprocessing tokens, they remain separate until the end of preprocessing.  Macros that generate two consecutive tokens insert whitespace to keep them separate, if necessary.  For example,

     #define foo() bar
     foo()baz
          ==> bar baz
     not
          ==> barbaz

The only exception is with the ## preprocessing operator, which pastes tokens together (see Concatenation).

Preprocessing treats the null character (code 0) as whitespace, but generates a warning for it because it may be invisible to the user (many terminals do not display it at all) and its presence in the file is probably a mistake.

Header Files
============

A header file is a file of C code, typically containing C declarations and macro definitions (see Macros), to be shared between several source files.  You request the use of a header file in your program by including it, with the C preprocessing directive #include.

Header files serve two purposes.

  * System header files declare the interfaces to parts of the operating system.  You include them in your program to supply the definitions and declarations that you need to invoke system calls and libraries.

  * Program-specific header files contain declarations for interfaces between the source files of a particular program.  It is a good idea to create a header file for related declarations and macro definitions if all or most of them are needed in several different source files.

Including a header file produces the same results as copying the header file into each source file that needs it.  Such copying would be time-consuming and error-prone.  With a header file, the related declarations appear in only one place.  If they need to be changed, you can change them in one place, and programs that include the header file will then automatically use the new version when next recompiled.  The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to change one copy will result in inconsistencies within a program.

In C, the usual convention is to give header files names that end with .h.  It is most portable to use only letters, digits, dashes, and underscores in header file names, and at most one dot.

The operation of including another source file isn't actually limited to the sort of code we put into header files.  You can put any sort of C code into a separate file, then use #include to copy it virtually into other C source files.  But that is a strange thing to do.

#include Syntax
---------------

You can specify inclusion of user and system header files with the preprocessing directive #include.  It has two variants:

#include <FILE>
     This variant is used for system header files.  It searches for a file named FILE in a standard list of system directories.  You can prepend directories to this list with the -I option (see Invoking GCC (Using the GNU Compiler Collection)).

#include "FILE"
     This variant is used for header files of your own program.  It searches for a file named FILE first in the directory containing the current file, then in the quote directories, then the same directories used for <FILE>.  You can prepend directories to the list of quote directories with the -iquote option.

The argument of #include, whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not recognized, and macro names are not expanded.  Thus, #include <x/*y> specifies inclusion of a system header file named x/*y.

However, if backslashes occur within FILE, they are considered ordinary text characters, not escape characters: character escape sequences such as used in string constants in C are not meaningful here.  Thus, #include "x\n\\y" specifies a filename containing three backslashes.  By the same token, there is no way to escape " or > to include it in the header file name if it would instead end the file name.

Some systems interpret \ as a file name component separator. All these systems also interpret / the same way.  It is most portable to use only /.

It is an error to put anything other than comments on the #include line after the file name.

#include Operation
------------------

The #include directive works by scanning the specified header file as input before continuing with the rest of the current file. The result of preprocessing consists of the text already generated, followed by the result of preprocessing the included file, followed by whatever results from the text after the #include directive. For example, if you have a header file header.h as follows,

     char *test (void);

and a main program called program.c that uses the header file, like this,

     int x;
     #include "header.h"

     int
     main (void)
     {
       puts (test ());
     }

the result is equivalent to putting this text in program.c:

     int x;
     char *test (void);

     int
     main (void)
     {
       puts (test ());
     }

Included files are not limited to declarations and macro definitions; those are merely the typical uses.  Any fragment of a C program can be included from another file.  The include file could even contain the beginning of a statement that is concluded in the containing file, or the end of a statement that was started in the including file.  However, an included file must consist of complete tokens.  Comments and string literals that have not been closed by the end of an included file are invalid.  For error recovery, the compiler terminates them at the end of the file.

To avoid confusion, it is best if header files contain only complete syntactic units---function declarations or definitions, type declarations, etc.

The line following the #include directive is always treated as a separate line, even if the included file lacks a final newline. There is no problem putting a preprocessing directive there.

Search Path
-----------

GCC looks in several different places for header files to be included. On the GNU system, and Unix systems, the default directories for system header files are:

     LIBDIR/gcc/TARGET/VERSION/include
     /usr/local/include
     LIBDIR/gcc/TARGET/VERSION/include-fixed
     LIBDIR/TARGET/include
     /usr/include/TARGET
     /usr/include

The list may be different in some operating systems.  Other directories are added for C++.

In the above, TARGET is the canonical name of the system GCC was configured to compile code for; often but not always the same as the canonical name of the system it runs on.  VERSION is the version of GCC in use.

You can add to this list with the -IDIR command-line option.  All the directories named by -I are searched, in left-to-right order, before the default directories.  The only exception is when dir is already searched by default.  In this case, the option is ignored and the search order for system directories remains unchanged.

Duplicate directories are removed from the quote and bracket search chains before the two chains are merged to make the final search chain. Thus, it is possible for a directory to occur twice in the final search chain if it was specified in both the quote and bracket chains.

You can prevent GCC from searching any of the default directories with the -nostdinc option.  This is useful when you are compiling an operating system kernel or some other program that does not use the standard C library facilities, or the standard C library itself. -I options are not ignored as described above when -nostdinc is in effect.

GCC looks for headers requested with #include "FILE" first in the directory containing the current file, then in the quote directories specified by -iquote options, then in the same places it looks for a system header.  For example, if /usr/include/sys/stat.h contains #include "types.h", GCC looks for types.h first in /usr/include/sys, then in the quote directories and then in its usual search path.

#line (see Line Control) does not change GCC's idea of the directory containing the current file.

The -I- is an old-fashioned, deprecated way to specify the quote directories.  To look for headers in a directory named -, specify -I./-.  There are several more ways to adjust the header search path.  See Invoking GCC (Using the GNU Compiler Collection).

Once-Only Headers
-----------------

If a header file happens to be included twice, the compiler will process its contents twice.  This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice.

The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this:

     /* File foo.  */
     #ifndef FILE_FOO_SEEN
     #define FILE_FOO_SEEN

     THE ENTIRE FILE

     #endif /* !FILE_FOO_SEEN */

This construct is commonly known as a wrapper #ifndef.  When the header is included again, the conditional will be false, because FILE_FOO_SEEN is defined.  Preprocessing skips over the entire contents of the file, so that compilation will never ``see'' the file contents twice in one module.

GCC optimizes this case even further.  It remembers when a header file has a wrapper #ifndef.  If a subsequent #include specifies that header, and the macro in the #ifndef is still defined, it does not bother to rescan the file at all.

You can put comments in the header file outside the wrapper.  They do not interfere with this optimization.

The macro FILE_FOO_SEEN is called the controlling macro or guard macro.  In a user header file, the macro name should not begin with _.  In a system header file, it should begin with __ (or _ followed by an upper-case letter) to avoid conflicts with user programs.  In any kind of header file, the macro name should contain the name of the file and some additional text, to avoid conflicts with other header files.

Computed Includes
-----------------

Sometimes it is necessary to select one of several different header files to be included into your program.  They might specify configuration parameters to be used on different sorts of operating systems, for instance.  You could do this with a series of conditionals,

     #if SYSTEM_1
     # include "system_1.h"
     #elif SYSTEM_2
     # include "system_2.h"
     #elif SYSTEM_3
     /* ... */
     #endif

That rapidly becomes tedious.  Instead, GNU C offers the ability to use a macro for the header name.  This is called a computed include. Instead of writing a header name as the direct argument of #include, you simply put a macro name there instead:

     #define SYSTEM_H "system_1.h"
     /* ... */
     #include SYSTEM_H

SYSTEM_H is expanded, then system_1.h is included as if the #include had been written with that name.  SYSTEM_H could be defined by your Makefile with a -D option.

You must be careful when you define such a macro.  #define saves tokens, not text.  GCC has no way of knowing that the macro will be used as the argument of #include, so it generates ordinary tokens, not a header name.  This is unlikely to cause problems if you use double-quote includes, which are syntactically similar to string constants.  If you use angle brackets, however, you may have trouble.

The syntax of a computed include is actually a bit more general than the above.  If the first non-whitespace character after #include is not " or <, then the entire line is macro-expanded like running text would be.

If the line expands to a single string constant, the contents of that string constant are the file to be included.  Preprocessing does not re-examine the string for embedded quotes, but neither does it process backslash escapes in the string.  Therefore

     #define HEADER "a\"b"
     #include HEADER

looks for a file named a\"b.  Preprocessing searches for the file according to the rules for double-quoted includes.

If the line expands to a token stream beginning with a < token and including a > token, then the tokens between the < and the first > are combined to form the filename to be included. Any whitespace between tokens is reduced to a single space; then any space after the initial < is retained, but a trailing space before the closing > is ignored.  Preprocessing searches for the file according to the rules for angle-bracket includes.

In either case, if there are any tokens on the line after the file name, an error occurs and the directive is not processed.  It is also an error if the result of expansion does not match either of the two expected forms.

These rules are implementation-defined behavior according to the C standard.  To minimize the risk of different compilers interpreting your computed includes differently, we recommend you use only a single object-like macro that expands to a string constant.  That also makes it clear to people reading your program.

Macros
======

A macro is a fragment of code that has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros.  They differ mostly in what they look like when they are used.  Object-like macros resemble data objects when used, function-like macros resemble function calls.

You may define any valid identifier as a macro, even if it is a C keyword.  In the preprocessing stage, GCC does not know anything about keywords.  This can be useful if you wish to hide a keyword such as const from an older compiler that does not understand it. However, the preprocessing operator defined (see defined) can never be defined as a macro, and C++'s named operators (see C++ Named Operators (Using the GNU Compiler Collection)) cannot be macros when compiling C++ code.

The operator # is used in macros for stringification of an argument (see Stringification), and ## is used for concatenation of arguments into larger tokens (see Concatenation)

Object-like Macros
------------------

An object-like macro is a simple identifier that will be replaced by a code fragment.  It is called object-like because in most cases the use of the macro looks like reference to a data object in code that uses it.  These macros are most commonly used to give symbolic names to numeric constants.

The way to define macros with the #define directive. #define is followed by the name of the macro and then the token sequence it should be an abbreviation for, which is variously referred to as the macro's body, expansion or replacement list.  For example,

     #define BUFFER_SIZE 1024

defines a macro named BUFFER_SIZE as an abbreviation for the token 1024.  If somewhere after this #define directive there comes a C statement of the form

     foo = (char *) malloc (BUFFER_SIZE);

then preprocessing will recognize and expand the macro BUFFER_SIZE, so that compilation will see the tokens:

     foo = (char *) malloc (1024);

By convention, macro names are written in upper case.  Programs are easier to read when it is possible to tell at a glance which names are macros.  Macro names that start with __ are reserved for internal uses, and many of them are defined automatically, so don't define such macro names unless you really know what you're doing. Likewise for macro names that start with _ and an upper-case letter.

The macro's body ends at the end of the #define line.  You may continue the definition onto multiple lines, if necessary, using backslash-newline.  When the macro is expanded, however, it will all come out on one line.  For example,

     #define NUMBERS 1, \
                     2, \
                     3
     int x[] = { NUMBERS };
          ==> int x[] = { 1, 2, 3 };

The most common visible consequence of this is surprising line numbers in error messages.

There is no restriction on what can go in a macro body provided it decomposes into valid preprocessing tokens.  Parentheses need not balance, and the body need not resemble valid C code.  (If it does not, you may get error messages from the C compiler when you use the macro.)

Preprocessing scans the program sequentially.  A macro definition takes effect right after its appearance.  Therefore, the following input

     foo = X;
     #define X 4
     bar = X;

produces

     foo = X;
     bar = 4;

When preprocessing expands a macro name, the macro's expansion replaces the macro invocation, then the expansion is examined for more macros to expand.  For example,

     #define TABLESIZE BUFSIZE
     #define BUFSIZE 1024
     TABLESIZE
          ==> BUFSIZE
          ==> 1024

TABLESIZE is expanded first to produce BUFSIZE, then that macro is expanded to produce the final result, 1024.

Notice that BUFSIZE was not defined when TABLESIZE was defined.  The #define for TABLESIZE uses exactly the expansion you specify---in this case, BUFSIZE---and does not check to see whether it too contains macro names.  Only when you use TABLESIZE is the result of its expansion scanned for more macro names.

This makes a difference if you change the definition of BUFSIZE at some point in the source file.  TABLESIZE, defined as shown, will always expand using the definition of BUFSIZE that is currently in effect:

     #define BUFSIZE 1020
     #define TABLESIZE BUFSIZE
     #undef BUFSIZE
     #define BUFSIZE 37

Now TABLESIZE expands (in two stages) to 37.

If the expansion of a macro contains its own name, either directly or via intermediate macros, it is not expanded again when the expansion is examined for more macros.  This prevents infinite recursion. See Self-Referential Macros, for the precise details.

Function-like Macros
--------------------

You can also define macros whose use looks like a function call. These are called function-like macros.  To define one, use the #define directive with a pair of parentheses immediately after the macro name.  For example,

     #define lang_init()  c_init()
     lang_init()
          ==> c_init()

A function-like macro is expanded only when its name appears with a pair of parentheses after it.  If you write just the name, without parentheses, it is left alone.  This can be useful when you have a function and a macro of the same name, and you wish to use the function sometimes.  Whitespace and line breaks before or between the parentheses are ignored when the macro is called.

     extern void foo(void);
     #define foo() /* optimized inline version */
     /* ... */
       foo();
       funcptr = foo;

Here the call to foo() expands the macro, but the function pointer funcptr gets the address of the real function foo.  If the macro were to be expanded there, it would cause a syntax error.

If you put spaces between the macro name and the parentheses in the macro definition, that does not define a function-like macro, it defines an object-like macro whose expansion happens to begin with a pair of parentheses.  Here is an example:

     #define lang_init ()    c_init()
     lang_init()
          ==> () c_init()()

The first two pairs of parentheses in this expansion come from the macro.  The third is the pair that was originally after the macro invocation.  Since lang_init is an object-like macro, it does not consume those parentheses.

Any name can have at most one macro definition at a time.  Thus, you can't define the same name as an object-like macro and a function-like macro at once.

Macro Arguments
---------------

Function-like macros can take arguments, just like true functions. To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like.  The parameters must be valid C identifiers, separated by commas and optionally whitespace.

To invoke a macro that takes arguments, you write the name of the macro followed by a list of actual arguments in parentheses, separated by commas.  The invocation of the macro need not be restricted to a single logical line---it can cross as many lines in the source file as you wish.  The number of arguments you give must match the number of parameters in the macro definition.  When the macro is expanded, each use of a parameter in its body is replaced by the tokens of the corresponding argument.  (The macro body is not required to use all of the parameters.)

As an example, here is a macro that computes the minimum of two numeric values, as it is defined in many C programs, and some uses.

     #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
       x = min(a, b);      ==> x = ((a) < (b) ? (a) : (b));
       y = min(1, 2);      ==> y = ((1) < (2) ? (1) : (2));
       z = min(a+28, *p);  ==> z = ((a+28) < (*p) ? (a+28) : (*p));

In this small example you can already see several of the dangers of macro arguments.  See Macro Pitfalls, for detailed explanations.

Leading and trailing whitespace in each argument is dropped, and all whitespace between the tokens of an argument is reduced to a single space.  Parentheses within each argument must balance; a comma within such parentheses does not end the argument.  However, there is no requirement for square brackets or braces to balance, and they do not prevent a comma from separating arguments.  Thus,

     macro (array[x = y, x + 1])

passes two arguments to macro: array[x = y and x + 1].  If you want to supply array[x = y, x + 1] as an argument, you can write it as array[(x = y, x + 1)], which is equivalent C code.  However, putting an assignment inside an array subscript is to be avoided anyway.

All arguments to a macro are completely macro-expanded before they are substituted into the macro body.  After substitution, the complete text is scanned again for macros to expand, including the arguments.  This rule may seem strange, but it is carefully designed so you need not worry about whether any function call is actually a macro invocation.  You can run into trouble if you try to be too clever, though.  See Argument Prescan, for detailed discussion.

For example, min (min (a, b), c) is first expanded to

       min (((a) < (b) ? (a) : (b)), (c))

and then to

     ((((a) < (b) ? (a) : (b))) < (c)
      ? (((a) < (b) ? (a) : (b)))
      : (c))

(The line breaks shown here for clarity are not actually generated.)

You can leave macro arguments empty without error, but many macros will then expand to invalid code.  You cannot leave out arguments entirely; if a macro takes two arguments, there must be exactly one comma at the top level of its argument list.  Here are some silly examples using min:

     min(, b)        ==> ((   ) < (b) ? (   ) : (b))
     min(a, )        ==> ((a  ) < ( ) ? (a  ) : ( ))
     min(,)          ==> ((   ) < ( ) ? (   ) : ( ))
     min((,),)       ==> (((,)) < ( ) ? ((,)) : ( ))

     min()      error--> macro "min" requires 2 arguments, but only 1 given
     min(,,)    error--> macro "min" passed 3 arguments, but takes just 2

Whitespace is not a preprocessing token, so if a macro foo takes one argument, foo () and foo ( ) both supply it an empty argument.

Macro parameters appearing inside string literals are not replaced by their corresponding actual arguments.

     #define foo(x) x, "x"
     foo(bar)        ==> bar, "x"

See the next subsection for how to insert macro arguments into a string literal.

The token following the macro call and the last token of the macro expansion do not become one token even if it looks like they could:

     #define foo()  abc
     foo()def        ==> abc def

Stringification
---------------

Sometimes you may want to convert a macro argument into a string constant.  Parameters are not replaced inside string constants, but you can use the # preprocessing operator instead.  When a macro parameter is used with a leading #, preprocessing replaces it with the literal text of the actual argument, converted to a string constant.  Unlike normal parameter replacement, the argument is not macro-expanded first.  This is called stringification.

There is no way to combine an argument with surrounding text and stringify it all together.  But you can write a series of string constants and stringified arguments.  After preprocessing replaces the stringified arguments with string constants, the consecutive string constants will be concatenated into one long string constant (see String Constants).

Here is an example that uses stringification and concatenation of string constants:

     #define WARN_IF(EXP) \
       do { if (EXP) \
               fprintf (stderr, "Warning: " #EXP "\n"); } \
       while (0)

     WARN_IF (x == 0);
          ==>
       do { if (x == 0)
               fprintf (stderr, "Warning: " "x == 0" "\n"); }
       while (0);

The argument for EXP is substituted once, as is, into the if statement, and once, stringified, into the argument to fprintf.  If x were a macro, it would be expanded in the if statement but not in the string.

The do and while (0) are a kludge to make it possible to write WARN_IF (ARG);.  The resemblance of WARN_IF to a function makes that a natural way to write it. See Swallowing the Semicolon.

Stringification in C involves more than putting double-quote characters around the fragment.  It also backslash-escapes the quotes surrounding embedded string constants, and all backslashes within string and character constants, in order to get a valid C string constant with the proper contents.  Thus, stringifying p = "foo\n"; results in "p = \"foo\\n\";".  However, backslashes that are not inside string or character constants are not duplicated: \n by itself stringifies to "\n".

All leading and trailing whitespace in text being stringified is ignored.  Any sequence of whitespace in the middle of the text is converted to a single space in the stringified result.  Comments are replaced by whitespace long before stringification happens, so they never appear in stringified text.

There is no way to convert a macro argument into a character constant.

To stringify the result of expansion of a macro argument, you have to use two levels of macros, like this:

     #define xstr(S) str(S)
     #define str(s) #s
     #define foo 4
     str (foo)
          ==> "foo"
     xstr (foo)
          ==> xstr (4)
          ==> str (4)
          ==> "4"

s is stringified when it is used in str, so it is not macro-expanded first.  But S is an ordinary argument to xstr, so it is completely macro-expanded before xstr itself is expanded (see Argument Prescan).  Therefore, by the time str gets to its argument text, that text already been macro-expanded.

Concatenation
-------------

It is often useful to merge two tokens into one while expanding macros. This is called token pasting or token concatenation.  The ## preprocessing operator performs token pasting.  When a macro is expanded, the two tokens on either side of each ## operator are combined into a single token, which then replaces the ## and the two original tokens in the macro expansion.  Usually both will be identifiers, or one will be an identifier and the other a preprocessing number.  When pasted, they make a longer identifier.

Concatenation into an identifier isn't the only valid case.  It is also possible to concatenate two numbers (or a number and a name, such as 1.5 and e3) into a number.  Also, multi-character operators such as += can be formed by token pasting.

However, two tokens that don't together form a valid token cannot be pasted together.  For example, you cannot concatenate x with +, not in either order.  Trying this issues a warning and keeps the two tokens separate.  Whether it puts white space between the tokens is undefined.  It is common to find unnecessary uses of ## in complex macros.  If you get this warning, it is likely that you can simply remove the ##.

The tokens combined by ## could both come from the macro body, but then you could just as well write them as one token in the first place. Token pasting is useful when one or both of the tokens comes from a macro argument.  If either of the tokens next to an ## is a parameter name, it is replaced by its actual argument before ## executes.  As with stringification, the actual argument is not macro-expanded first.  If the argument is empty, that ## has no effect.

Keep in mind that preprocessing converts comments to whitespace before it looks for uses of macros.  Therefore, you cannot create a comment by concatenating / and *.  You can put as much whitespace between ## and its operands as you like, including comments, and you can put comments in arguments that will be concatenated.

It is an error to use ## at the beginning or end of a macro body.

Multiple ## operators are handled left-to-right, so that 1 ## e ## -2 pastes into 1e-2.  (Right-to-left processing would first generate e-2, which is an invalid token.) When # and ## are used together, they are all handled left-to-right.

Consider a C program that interprets named commands.  There probably needs to be a table of commands, perhaps an array of structures declared as follows:

     struct command
     {
       char *name;
       void (*function) (void);
     };

     struct command commands[] =
     {
       { "quit", quit_command },
       { "help", help_command },
       /* ... */
     };

It would be cleaner not to have to write each command name twice, once in the string constant and once in the function name.  A macro that takes the name of a command as an argument can make this unnecessary. It can create the string constant with stringification, and the function name by concatenating the argument with _command. Here is how it is done:

     #define COMMAND(NAME)  { #NAME, NAME ## _command }

     struct command commands[] =
     {
       COMMAND (quit),
       COMMAND (help),
       /* ... */
     };

Variadic Macros
---------------

A macro can be declared to accept a variable number of arguments much as a function can.  The syntax for defining the macro is similar to that of a function.  Here is an example:

     #define eprintf(...) fprintf (stderr, __VA_ARGS__)

This kind of macro is called variadic.  When the macro is invoked, all the tokens in its argument list after the last named argument (this macro has none), including any commas, become the variable argument.  This sequence of tokens replaces the identifier __VA_ARGS__ in the macro body wherever it appears.  Thus, we have this expansion:

     eprintf ("%s:%d: ", input_file, lineno)
          ==>  fprintf (stderr, "%s:%d: ", input_file, lineno)

The variable argument is completely macro-expanded before it is inserted into the macro expansion, just like an ordinary argument.  You may use the # and ## operators to stringify the variable argument or to paste its leading or trailing token with another token.  (But see below for an important special case for ##.)

Warning: don't use the identifier __VA_ARGS__ for anything other than this.

If your macro is complicated, you may want a more descriptive name for the variable argument than __VA_ARGS__.  You can write an argument name immediately before the ...; that name is used for the variable argument. (GNU C extension.)  The eprintf macro above could be written thus:

     #define eprintf(args...) fprintf (stderr, args)

A variadic macro can have named arguments as well as variable arguments, so eprintf can be defined like this, instead:

     #define eprintf(format, ...) \
       fprintf (stderr, format, __VA_ARGS__)

This formulation is more descriptive, but what if you want to specify a format string that takes no arguments?  In GNU C, you can omit the comma before the variable arguments if they are empty, but that puts an extra comma in the expansion:

     eprintf ("success!\n")
          ==> fprintf(stderr, "success!\n", );

That's an error in the call to fprintf.

To get rid of that comma, the ## token paste operator has a special meaning when placed between a comma and a variable argument. (GNU C extension.)  If you write

     #define eprintf(format, ...) \
       fprintf (stderr, format, ##__VA_ARGS__)

then use the macro eprintf with empty variable arguments, ## deletes the preceding comma.

     eprintf ("success!\n")
          ==> fprintf(stderr, "success!\n");

This does not happen if you pass an empty argument, nor does it happen if the token preceding ## is anything other than a comma.

When the only macro parameter is a variable arguments parameter, and the macro call has no argument at all, it is not obvious whether that means an empty argument or a missing argument.  Should the comma be kept, or deleted?  The C standard says to keep the comma, but the preexisting GNU C extension deleted the comma.  Nowadays, GNU C retains the comma when implementing a specific C standard, and deletes it otherwise.

C99 mandates that the only place the identifier __VA_ARGS__ can appear is in the replacement list of a variadic macro.  It may not be used as a macro name, macro parameter name, or within a different type of macro.  It may also be forbidden in open text; the standard is ambiguous.  We recommend you avoid using that name except for its special purpose.

Variadic macros where you specify the parameter name is a GNU C feature that has been supported for a long time.  Standard C, as of C99, supports only the form where the parameter is called __VA_ARGS__.  For portability to previous versions of GNU C you should use only named variable argument parameters.  On the other hand, for portability to other C99 compilers, you should use only __VA_ARGS__.

Predefined Macros
-----------------

Several object-like macros are predefined; you use them without supplying their definitions.  Here we explain the ones user programs often need to use.  Many other macro names starting with __ are predefined; in general, you should not define such macro names yourself.

__FILE__
     This macro expands to the name of the current input file, in the form of a C string constant.  This is the full name by which the GCC opened the file, not the short name specified in #include or as the input file name argument.  For example, "/usr/local/include/myheader.h" is a possible expansion of this macro.

__LINE__
     This macro expands to the current input line number, in the form of a decimal integer constant.  While we call it a predefined macro, it's a pretty strange macro, since its ``definition'' changes with each new line of source code.

__func__
__FUNCTION__
     These names are like variables that have as value a string containing the name of the current function definition.  They are not really macros, but this is the best place to mention them.

     __FUNCTION__ is the name that has been defined in GNU C since time immemorial; __func__ is defined by the C standard. With the following conditionals, you can use whichever one is defined.

          #if __STDC_VERSION__ < 199901L
          # if __GNUC__ >= 2
          #  define __func__ __FUNCTION__
          # else
          #  define __func__ "<unknown>"
          # endif
          #endif

__PRETTY_FUNCTION__
     This is equivalent to __FUNCTION__ in C, but in C++ the string includes argument type information as well. It is a GNU C extension.

Those features are useful in generating an error message to report an inconsistency detected by the program; the message can state the source line where the inconsistency was detected.  For example,

     fprintf (stderr, "Internal error: "
                      "negative string length "
                      "in function %s "
                      "%d at %s, line %d.",
              __func__, length, __FILE__, __LINE__);

A #line directive changes __LINE__, and may change __FILE__ as well.  See Line Control.

__DATE__
     This macro expands to a string constant that describes the date of compilation.  The string constant contains eleven characters and looks like "Feb 12 1996".  If the day of the month is just one digit, an extra space precedes it so that the date is always eleven characters.

     If the compiler cannot determine the current date, it emits a warning messages (once per compilation) and __DATE__ expands to "??? ?? ????".

     We deprecate the use of __DATE__ for the sake of reproducible compilation.

__TIME__
     This macro expands to a string constant that describes the time of compilation.  The string constant contains eight characters and looks like "23:59:01".

     If the compiler cannot determine the current time, it emits a warning message (once per compilation) and __TIME__ expands to "??:??:??".

     We deprecate the use of __TIME__ for the sake of reproducible compilation.

__STDC__
     In normal operation, this macro expands to the constant 1, to signify that this compiler implements ISO Standard C.

__STDC_VERSION__
     This macro expands to the C Standard's version number, a long integer constant of the form YYYYMML where YYYY and MM are the year and month of the Standard version.  This states which version of the C Standard the compiler implements.

     The current default value is 201112L, which signifies the C 2011 standard.

__STDC_HOSTED__
     This macro is defined, with value 1, if the compiler's target is a hosted environment.  A hosted environment provides the full facilities of the standard C library.

The rest of the predefined macros are GNU C extensions.

__COUNTER__
     This macro expands to sequential integral values starting from 0.  In other words, each time the program uses this macro, it generates the next successive integer.  This, with the ## operator, provides a convenient means for macros to generate unique identifiers.

__GNUC__
__GNUC_MINOR__
__GNUC_PATCHLEVEL__
     These macros expand to the major version, minor version, and patch level of the compiler, as integer constants.  For example, GCC 3.2.1 expands __GNUC__ to 3, __GNUC_MINOR__ to 2, and __GNUC_PATCHLEVEL__ to 1.

     If all you need to know is whether or not your program is being compiled by GCC, or a non-GCC compiler that claims to accept the GNU C extensions, you can simply test __GNUC__.  If you need to write code that depends on a specific version, you must check more carefully.  Each change in the minor version resets the patch level to zero; each change in the major version (which happens rarely) resets the minor version and the patch level to zero.  To use the predefined macros directly in the conditional, write it like this:

          /* Test for version 3.2.0 or later. */
          #if __GNUC__ > 3 || \
              (__GNUC__ == 3 && (__GNUC_MINOR__ > 2 || \
                                 (__GNUC_MINOR__ == 2 && \
                                  __GNUC_PATCHLEVEL__ > 0))

     Another approach is to use the predefined macros to calculate a single number, then compare that against a threshold:

          #define GCC_VERSION (__GNUC__ * 10000 \
                               + __GNUC_MINOR__ * 100 \
                               + __GNUC_PATCHLEVEL__)
          /* ... */
          /* Test for GCC > 3.2.0 */
          #if GCC_VERSION > 30200

     Many people find this form easier to understand.

__VERSION__
     This macro expands to a string constant that describes the version of the compiler in use.  You should not rely on its contents' having any particular form, but you can count on it to contain at least the release number.

__TIMESTAMP__
     This macro expands to a string constant that describes the date and time of the last modification of the current source file. The string constant contains abbreviated day of the week, month, day of the month, time in hh:mm:ss form, and the year, in the format "Sun Sep 16 01:03:52 1973".  If the day of the month is less than 10, it is padded with a space on the left.

     If GCC cannot determine that information date, it emits a warning message (once per compilation) and __TIMESTAMP__ expands to "??? ??? ?? ??:??:?? ????".

     We deprecate the use of this macro for the sake of reproducible compilation.

Undefining and Redefining Macros
--------------------------------

You can undefine a macro with the #undef directive. #undef takes a single argument, the name of the macro to undefine.  You use the bare macro name, even if the macro is function-like.  It is an error if anything appears on the line after the macro name.  #undef has no effect if the name is not a macro.

     #define FOO 4
     x = FOO;        ==> x = 4;
     #undef FOO
     x = FOO;        ==> x = FOO;

Once a macro has been undefined, that identifier may be redefined as a macro by a subsequent #define directive.  The new definition need not have any resemblance to the old definition.

You can define a macro again without first undefining it only if the new definition is effectively the same as the old one. Two macro definitions are effectively the same if:

  * Both are the same type of macro (object- or function-like).

  * All the tokens of the replacement list are the same.

  * If there are any parameters, they are the same.

  * Whitespace appears in the same places in both.  It need not be exactly the same amount of whitespace, though.  Remember that comments count as whitespace.

These definitions are effectively the same:

     #define FOUR (2 + 2)
     #define FOUR         (2    +    2)
     #define FOUR (2 /* two */ + 2)

but these are not:

     #define FOUR (2 + 2)
     #define FOUR ( 2+2 )
     #define FOUR (2 * 2)
     #define FOUR(score,and,seven,years,ago) (2 + 2)

This allows two different header files to define a common macro.

You can redefine an existing macro with #define, but redefining an existing macro name with a different definition results in a warning.

Directives Within Macro Arguments
---------------------------------

GNU C permits and handles preprocessing directives in the text provided as arguments for a macro.  That case is undefined in the C standard. but in GNU C conditional directives in macro arguments are clear and valid.

A paradoxical case is to redefine a macro within the call to that same macro.  What happens is, the new definition takes effect in time for pre-expansion of all the arguments, then the original definition is expanded to replace the call.  Here is a pathological example:

     #define f(x) x x
     f (first f second
     #undef f
     #define f 2
     f)

which expands to

     first 2 second 2 first 2 second 2

with the semantics described above.  We suggest you avoid writing code which does this sort of thing.

Macro Pitfalls
--------------

In this section we describe some special rules that apply to macros and macro expansion, and point out certain cases in which the rules have counter-intuitive consequences that you must watch out for.

Misnesting
..........

When a macro is called with arguments, the arguments are substituted into the macro body and the result is checked, together with the rest of the input file, for more macro calls.  It is possible to piece together a macro call coming partially from the macro body and partially from the arguments.  For example,

     #define twice(x) (2*(x))
     #define call_with_1(x) x(1)
     call_with_1 (twice)
          ==> twice(1)
          ==> (2*(1))

Macro definitions do not have to have balanced parentheses.  By writing an unbalanced open parenthesis in a macro body, it is possible to create a macro call that begins inside the macro body but ends outside of it. For example,

     #define strange(file) fprintf (file, "%s %d",
     /* ... */
     strange(stderr) p, 35)
          ==> fprintf (stderr, "%s %d", p, 35)

The ability to piece together a macro call can be useful, but the use of unbalanced open parentheses in a macro body is just confusing, and should be avoided.

Operator Precedence Problems
............................

You may have noticed that in most of the macro definition examples shown above, each occurrence of a macro parameter name had parentheses around it.  In addition, another pair of parentheses usually surrounds the entire macro definition.  Here is why it is best to write macros that way.

Suppose you define a macro as follows,

     #define ceil_div(x, y) (x + y - 1) / y

whose purpose is to divide, rounding up.  (One use for this operation is to compute how many int objects are needed to hold a certain number of char objects.)  Then suppose it is used as follows:

     a = ceil_div (b & c, sizeof (int));
          ==> a = (b & c + sizeof (int) - 1) / sizeof (int);

This does not do what is intended.  The operator-precedence rules of C make it equivalent to this:

     a = (b & (c + sizeof (int) - 1)) / sizeof (int);

What we want is this:

     a = ((b & c) + sizeof (int) - 1)) / sizeof (int);

Defining the macro as

     #define ceil_div(x, y) ((x) + (y) - 1) / (y)

provides the desired result.

Unintended grouping can result in another way.  Consider sizeof ceil_div(1, 2).  That has the appearance of a C expression that would compute the size of the type of ceil_div (1, 2), but in fact it means something very different.  Here is what it expands to:

     sizeof ((1) + (2) - 1) / (2)

This would take the size of an integer and divide it by two.  The precedence rules have put the division outside the sizeof when it was intended to be inside.

Parentheses around the entire macro definition prevent such problems. Here, then, is the recommended way to define ceil_div:

     #define ceil_div(x, y) (((x) + (y) - 1) / (y))

Swallowing the Semicolon
........................

Often it is desirable to define a macro that expands into a compound statement.  Consider, for example, the following macro, that advances a pointer (the parameter p says where to find it) across whitespace characters:

     #define SKIP_SPACES(p, limit)  \
     { char *lim = (limit);         \
       while (p < lim) {            \
         if (*p++ != ' ') {         \
           p--; break; }}}

Here backslash-newline is used to split the macro definition, which must be a single logical line, so that it resembles the way such code would be laid out if not part of a macro definition.

A call to this macro might be SKIP_SPACES (p, lim).  Strictly speaking, the call expands to a compound statement, which is a complete statement with no need for a semicolon to end it.  However, since it looks like a function call, it minimizes confusion if you can use it like a function call, writing a semicolon afterward, as in SKIP_SPACES (p, lim);

This can cause trouble before else statements, because the semicolon is actually a null statement.  Suppose you write

     if (*p != 0)
       SKIP_SPACES (p, lim);
     else /* ... */

The presence of two statements---the compound statement and a null statement---in between the if condition and the else makes invalid C code.

The definition of the macro SKIP_SPACES can be altered to solve this problem, using a do ... while statement.  Here is how:

     #define SKIP_SPACES(p, limit)     \
     do { char *lim = (limit);         \
          while (p < lim) {            \
            if (*p++ != ' ') {         \
              p--; break; }}}          \
     while (0)

Now SKIP_SPACES (p, lim); expands into

     do { /* ... */ } while (0);

which is one statement.  The loop executes exactly once; most compilers generate no extra code for it.

Duplication of Side Effects
...........................

Many C programs define a macro min, for ``minimum'', like this:

     #define min(X, Y)  ((X) < (Y) ? (X) : (Y))

When you use this macro with an argument containing a side effect, as shown here,

     next = min (x + y, foo (z));

it expands as follows:

     next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));

where x + y has been substituted for X and foo (z) for Y.

The function foo is used only once in the statement as it appears in the program, but the expression foo (z) has been substituted twice into the macro expansion.  As a result, foo might be called twice when the statement is executed.  If it has side effects or if it takes a long time to compute, that may be undesirable.  We say that min is an unsafe macro.

The best solution to this problem is to define min in a way that computes the value of foo (z) only once.  In general, that requires using __auto_type (see Auto Type).  How to use it for this is described in the following section.  See Macros and Auto Type.

Otherwise, you will need to be careful when using the macro min.  For example, you can calculate the value of foo (z), save it in a variable, and use that variable in min:

     #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
     /* ... */
     {
       int tem = foo (z);
       next = min (x + y, tem);
     }

(where we assume that foo returns type int).

When the repeated value appears as the condition of the ?: operator and again as its IFTRUE expression, you can avoid repeated execution by omitting the IFTRUE expression, like this:

     #define x_or_y(X, Y)  ((X) ? : (Y))

In GNU C, this expands to use the first macro argument's value if that isn't zero.  If that's zero, it compiles the second argument and uses that value.  See Conditional Expression.

Using __auto_type for Local Variables
.....................................

The operator __auto_type makes it possible to define macros that can work on any data type even though they need to generate local variable declarations.  See Auto Type.

For instance, here's how to define a safe ``maximum'' macro that operates on any arithmetic type and computes each of its arguments exactly once:

     #define max(a,b) \
       ({ __auto_type _a = (a); \
           __auto_type _b = (b); \
         _a > _b ? _a : _b; })

The ({ ... }) notation produces statement expression---a statement that can be used as an expression (see Statement Exprs).  Its value is the value of its last statement.  This permits us to define local variables and store each argument value into one.

The reason for using names that start with underscores for the local variables is to avoid conflicts with variable names that occur within the expressions that are substituted for a and b. Underscore followed by a lower case letter won't be predefined by the system in any way.

Self-Referential Macros
.......................

A self-referential macro is one whose name appears in its definition.  Recall that all macro definitions are rescanned for more macros to replace.  If the self-reference were considered a use of the macro, it would produce an infinitely large expansion.  To prevent this, the self-reference is not considered a macro call: preprocessing leaves it unchanged.  Consider an example:

     #define foo (4 + foo)

where foo is also a variable in your program.

Following the ordinary rules, each reference to foo will expand into (4 + foo); then this will be rescanned and will expand into (4 + (4 + foo)); and so on until the computer runs out of memory.

The self-reference rule cuts this process short after one step, at (4 + foo).  Therefore, this macro definition has the possibly useful effect of causing the program to add 4 to the value of foo wherever foo is referred to.

In most cases, it is a bad idea to take advantage of this feature.  A person reading the program who sees that foo is a variable will not expect that it is a macro as well.  The reader will come across the identifier foo in the program and think its value should be that of the variable foo, whereas in fact the value is four greater.

It is useful to make a macro definition that expands to the macro name itself.  If you write

     #define EPERM EPERM

then the macro EPERM expands to EPERM.  Effectively, preprocessing leaves it unchanged in the source code.  You can tell that it's a macro with #ifdef.  You might do this if you want to define numeric constants with an enum, but have #ifdef be true for each constant.

If a macro x expands to use a macro y, and the expansion of y refers to the macro x, that is an indirect self-reference of x.  x is not expanded in this case either.  Thus, if we have

     #define x (4 + y)
     #define y (2 * x)

then x and y expand as follows:

     x    ==> (4 + y)
          ==> (4 + (2 * x))

     y    ==> (2 * x)
          ==> (2 * (4 + y))

Each macro is expanded when it appears in the definition of the other macro, but not when it indirectly appears in its own definition.

Argument Prescan
................

Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens.  After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.

Most of the time, this has no effect.  If the argument contained any macro calls, they were expanded during the first scan.  The result therefore contains no macro calls, so the second scan does not change it.  If the argument were substituted as given, with no prescan, the single remaining scan would find the same macro calls and produce the same results.

You might expect the double scan to change the results when a self-referential macro is used in an argument of another macro (see Self-Referential Macros): the self-referential macro would be expanded once in the first scan, and a second time in the second scan. However, this is not what happens.  The self-references that do not expand in the first scan are marked so that they will not expand in the second scan either.

You might wonder, ``Why mention the prescan, if it makes no difference? And why not skip it and make preprocessing go faster?''  The answer is that the prescan does make a difference in three special cases:

  * Nested calls to a macro.

     We say that nested calls to a macro occur when a macro's argument contains a call to that very macro.  For example, if f is a macro that expects one argument, f (f (1)) is a nested pair of calls to f.  The desired expansion is made by expanding f (1) and substituting that into the definition of f.  The prescan causes the expected result to happen.  Without the prescan, f (1) itself would be substituted as an argument, and the inner use of f would appear during the main scan as an indirect self-reference and would not be expanded.

  * Macros that call other macros that stringify or concatenate.

     If an argument is stringified or concatenated, the prescan does not occur.  If you want to expand a macro, then stringify or concatenate its expansion, you can do that by causing one macro to call another macro that does the stringification or concatenation.  For instance, if you have

          #define AFTERX(x) X_ ## x
          #define XAFTERX(x) AFTERX(x)
          #define TABLESIZE 1024
          #define BUFSIZE TABLESIZE

     then AFTERX(BUFSIZE) expands to X_BUFSIZE, and XAFTERX(BUFSIZE) expands to X_1024.  (Not to X_TABLESIZE.  Prescan always does a complete expansion.)

  * Macros used in arguments, whose expansions contain unshielded commas.

     This can cause a macro expanded on the second scan to be called with the wrong number of arguments.  Here is an example:

          #define foo  a,b
          #define bar(x) lose(x)
          #define lose(x) (1 + (x))

     We would like bar(foo) to turn into (1 + (foo)), which would then turn into (1 + (a,b)).  Instead, bar(foo) expands into lose(a,b), which gives an error because lose requires a single argument.  In this case, the problem is easily solved by the same parentheses that ought to be used to prevent misnesting of arithmetic operations:

          #define foo (a,b)
          or
          #define bar(x) lose((x))

     The extra pair of parentheses prevents the comma in foo's definition from being interpreted as an argument separator.

Conditionals
============

A conditional is a preprocessing directive that controls whether or not to include a chunk of code in the final token stream that is compiled.  Preprocessing conditionals can test arithmetic expressions, or whether a name is defined as a macro, or both together using the special defined operator.

A preprocessing conditional in C resembles in some ways an if statement in C, but it is important to understand the difference between them.  The condition in an if statement is tested during the execution of your program.  Its purpose is to allow your program to behave differently from run to run, depending on the data it is operating on.  The condition in a preprocessing conditional directive is tested when your program is compiled.  Its purpose is to allow different code to be included in the program depending on the situation at the time of compilation.

Sometimes this distinction makes no practical difference.  GCC and other modern compilers often do test if statements when a program is compiled, if their conditions are known not to vary at run time, and eliminate code that can never be executed.  If you can count on your compiler to do this, you may find that your program is more readable if you use if statements with constant conditions (perhaps determined by macros).  Of course, you can only use this to exclude code, not type definitions or other preprocessing directives, and you can only do it if the file remains syntactically valid when that code is not used.

Uses of Conditional Directives
------------------------------

There are three usual reasons to use a preprocessing conditional.

  * A program may need to use different code depending on the machine or operating system it is to run on.  In some cases the code for one operating system may be erroneous on another operating system; for example, it might refer to data types or constants that do not exist on the other system.  When this happens, it is not enough to avoid executing the invalid code.  Its mere presence will cause the compiler to reject the program.  With a preprocessing conditional, the offending code can be effectively excised from the program when it is not valid.

  * You may want to be able to compile the same source file into two different programs.  One version might make frequent time-consuming consistency checks on its intermediate data, or print the values of those data for debugging, and the other not.

  * A conditional whose condition is always false is one way to exclude code from the program but keep it as a sort of comment for future reference.

Simple programs that do not need system-specific logic or complex debugging hooks generally will not need to use preprocessing conditionals.

Syntax of Preprocessing Conditionals
------------------------------------

A preprocessing conditional begins with a conditional directive: #if, #ifdef or #ifndef.

The #ifdef directive
....................

The simplest sort of conditional is

     #ifdef MACRO

     CONTROLLED TEXT

     #endif /* MACRO */

This block is called a conditional group.  The body, CONTROLLED TEXT, will be included in compilation if and only if MACRO is defined.  We say that the conditional succeeds if MACRO is defined, fails if it is not.

The CONTROLLED TEXT inside a conditional can include preprocessing directives.  They are executed only if the conditional succeeds.  You can nest conditional groups inside other conditional groups, but they must be completely nested.  In other words, #endif always matches the nearest #ifdef (or #ifndef, or #if).  Also, you cannot start a conditional group in one file and end it in another.

Even if a conditional fails, the CONTROLLED TEXT inside it is still run through initial transformations and tokenization.  Therefore, it must all be lexically valid C.  Normally the only way this matters is that all comments and string literals inside a failing conditional group must still be properly ended.

The comment following the #endif is not required, but it is a good practice if there is a lot of CONTROLLED TEXT, because it helps people match the #endif to the corresponding #ifdef.

Older programs sometimes put MACRO directly after the #endif without enclosing it in a comment.  This is invalid code according to the C standard, but it only causes a warning in GNU C. It never affects which #ifndef the #endif matches.

Sometimes you wish to use some code if a macro is not defined. You can do this by writing #ifndef instead of #ifdef. One common use of #ifndef is to include code only the first time a header file is included.  See Once-Only Headers.

Macro definitions can vary between compilations for several reasons. Here are some samples.

  * Some macros are predefined on each kind of machine (see System-specific Predefined Macros (Using the GNU Compiler Collection)).  This allows you to provide code specially tuned for a particular machine.

  * System header files define more macros, associated with the features they implement.  You can test these macros with conditionals to avoid using a system feature on a machine where it is not implemented.

  * Macros can be defined or undefined with the -D and -U command-line options when you compile the program.  You can arrange to compile the same source file into two different programs by choosing a macro name to specify which program you want, writing conditionals to test whether or how this macro is defined, and then controlling the state of the macro with command-line options, perhaps set in the file Makefile.  See Invoking GCC (Using the GNU Compiler Collection).

  * Your program might have a special header file (often called config.h) that is adjusted when the program is compiled.  It can define or not define macros depending on the features of the system and the desired capabilities of the program.  The adjustment can be automated by a tool such as autoconf, or done by hand.

The #if directive
.................

The #if directive allows you to test the value of an integer arithmetic expression, rather than the mere existence of one macro.  Its syntax is

     #if EXPRESSION

     CONTROLLED TEXT

     #endif /* EXPRESSION */

EXPRESSION is a C expression of integer type, subject to stringent restrictions so its value can be computed at compile time. It may contain

  * Integer constants.

  * Character constants, which are interpreted as they would be in normal code.

  * Arithmetic operators for addition, subtraction, multiplication, division, bitwise operations, shifts, comparisons, and logical operations (&& and ||).  The latter two obey the usual short-circuiting rules of standard C.

  * Macros.  All macros in the expression are expanded before actual computation of the expression's value begins.

  * Uses of the defined operator, which lets you check whether macros are defined in the middle of an #if.

  * Identifiers that are not macros, which are all considered to be the number zero.  This allows you to write #if MACRO instead of #ifdef MACRO, if you know that MACRO, when defined, will always have a nonzero value.  Function-like macros used without their function call parentheses are also treated as zero.

     In some contexts this shortcut is undesirable.  The -Wundef requests warnings for any identifier in an #if that is not defined as a macro.

Preprocessing does not know anything about the data types of C. Therefore, sizeof operators are not recognized in #if; sizeof is simply an identifier, and if it is not a macro, it stands for zero.  This is likely to make the expression invalid. Preprocessing does not recognize enum constants; they too are simply identifiers, so if they are not macros, they stand for zero.

Preprocessing calculates the value of EXPRESSION, and carries out all calculations in the widest integer type known to the compiler; on most machines supported by GNU C this is 64 bits.  This is not the same rule as the compiler uses to calculate the value of a constant expression, and may give different results in some cases.  If the value comes out to be nonzero, the #if succeeds and the CONTROLLED TEXT is compiled; otherwise it is skipped.

The defined test
................

The special operator defined is used in #if and #elif expressions to test whether a certain name is defined as a macro.  defined NAME and defined (NAME) are both expressions whose value is 1 if NAME is defined as a macro at the current point in the program, and 0 otherwise.  Thus,  #if defined MACRO is precisely equivalent to #ifdef MACRO.

defined is useful when you wish to test more than one macro for existence at once.  For example,

     #if defined (__arm__) || defined (__PPC__)

would succeed if either of the names __arm__ or __PPC__ is defined as a macro---in other words, when compiling for ARM processors or PowerPC processors.

Conditionals written like this:

     #if defined BUFSIZE && BUFSIZE >= 1024

can generally be simplified to just #if BUFSIZE >= 1024, since if BUFSIZE is not defined, it will be interpreted as having the value zero.

In GCC, you can include defined as part of another macro definition, like this:

     #define MACRO_DEFINED(X) defined X

     #if MACRO_DEFINED(BUFSIZE)

which would expand the #if expression to:

     #if defined BUFSIZE

Generating defined in this way is a GNU C extension.

The #else directive
...................

The #else directive can be added to a conditional to provide alternative text to be used if the condition fails.  This is what it looks like:

     #if EXPRESSION
     TEXT-IF-TRUE
     #else /* Not EXPRESSION */
     TEXT-IF-FALSE
     #endif /* Not EXPRESSION */

If EXPRESSION is nonzero, the TEXT-IF-TRUE is included and the TEXT-IF-FALSE is skipped.  If EXPRESSION is zero, the opposite happens.

You can use #else with #ifdef and #ifndef, too.

The #elif directive
...................

One common case of nested conditionals is used to check for more than two possible alternatives.  For example, you might have

     #if X == 1
     /* ... */
     #else /* X != 1 */
     #if X == 2
     /* ... */
     #else /* X != 2 */
     /* ... */
     #endif /* X != 2 */
     #endif /* X != 1 */

Another conditional directive, #elif, allows this to be abbreviated as follows:

     #if X == 1
     /* ... */
     #elif X == 2
     /* ... */
     #else /* X != 2 and X != 1*/
     /* ... */
     #endif /* X != 2 and X != 1*/

#elif stands for ``else if''.  Like #else, it goes in the middle of a conditional group and subdivides it; it does not require a matching #endif of its own.  Like #if, the #elif directive includes an expression to be tested.  The text following the #elif is processed only if the original #if-condition failed and the #elif condition succeeds.

More than one #elif can go in the same conditional group.  Then the text after each #elif is processed only if the #elif condition succeeds after the original #if and all previous #elif directives within it have failed.

#else is allowed after any number of #elif directives, but #elif may not follow #else.

Deleted Code
------------

If you replace or delete a part of the program but want to keep the old code in the file for future reference, commenting it out is not so straightforward in C.  Block comments do not nest, so the first comment inside the old code will end the commenting-out.  The probable result is a flood of syntax errors.

One way to avoid this problem is to use an always-false conditional instead.  For instance, put #if 0 before the deleted code and #endif after it.  This works even if the code being turned off contains conditionals, but they must be entire conditionals (balanced #if and #endif).

Some people use #ifdef notdef instead.  This is risky, because notdef might be accidentally defined as a macro, and then the conditional would succeed.  #if 0 can be counted on to fail.

Do not use #if 0 around text that is not C code.  Use a real comment, instead.  The interior of #if 0 must consist of complete tokens; in particular, single-quote characters must balance.  Comments often contain unbalanced single-quote characters (known in English as apostrophes).  These confuse #if 0.  They don't confuse /*.

Diagnostics
===========

The directive #error reports a fatal error.  The tokens forming the rest of the line following #error are used as the error message.

The usual place to use #error is inside a conditional that detects a combination of parameters that you know the program does not properly support.  For example,

     #if !defined(UNALIGNED_INT_ASM_OP) && defined(DWARF2_DEBUGGING_INFO)
     #error "DWARF2_DEBUGGING_INFO requires UNALIGNED_INT_ASM_OP."
     #endif

The directive #warning is like #error, but it reports a warning instead of an error.  The tokens following #warning are used as the warning message.

You might use #warning in obsolete header files, with a message saying which header file to use instead.

Neither #error nor #warning macro-expands its argument. Internal whitespace sequences are each replaced with a single space. The line must consist of complete tokens.  It is wisest to make the argument of these directives be a single string constant; this avoids problems with apostrophes and the like.

Line Control
============

Due to C's widespread availability and low-level nature, it is often used as the target language for translation of other languages, or for the output of lexical analyzers and parsers (e.g., lex/flex and yacc/bison).  Line control enables the user to track diagnostics back to the location in the original language.

The C compiler knows the location in the source file where each token came from: file name, starting line and column, and final line and column. (Column numbers are used only for error messages.)

When a program generates C source code, as the Bison parser generator does, often it copies some of that C code from another file.  For instance parts of the output from Bison are generated from scratch or come from a standard parser file, but Bison copies the rest from Bison's input file.  Errors in that code, at compile time or run time, should refer to that file, which is the real source code.  To make that happen, Bison generates line-control directives that the C compiler understands.

#line is a directive that specifies the original line number and source file name for subsequent code.  #line has three variants:

#line LINENUM
     LINENUM is a non-negative decimal integer constant.  It specifies the line number that should be reported for the following line of input.  Subsequent lines are counted from LINENUM.

#line LINENUM FILENAME
     LINENUM is the same as for the first form, and has the same effect.  In addition, FILENAME is a string constant that specifies the source file name.  Subsequent source lines are recorded as coming from that file, until something else happens to change that. FILENAME is interpreted according to the normal rules for a string constant.  Backslash escapes are interpreted, in contrast to #include.

#line ANYTHING ELSE
     ANYTHING ELSE is checked for macro calls, which are expanded. The result should match one of the above two forms.

#line directives alter the results of the __FILE__ and __LINE__ symbols from that point on.  See Predefined Macros.

Null Directive
==============

The null directive consists of a # followed by a newline, with only whitespace and comments in between.  It has no effect on the output of the compiler.