C preprocessor
Encyclopedia : C : CP : CPR : C preprocessor
The C preprocessor (cpp) is the preprocessor for the C programming language. It is invoked by the compiler to handle directives such as #include, #define, and #if. Since the language of such directives is not strictly specific to the grammar of C, the preprocessor can also be invoked independently to process another type of file.
The transformations it makes on its input form the first four so-called Phases of Translation. Though an implementation may choose to perform some or all phases simultaneously, it must behave as if it performed them one-by-one in order.
Phases
- Trigraph Replacement - The preprocessor replaces trigraph sequences with the characters they represent.
- Line Splicing - Physical source lines that are continued with escaped newline sequences are spliced to form logical lines.
- Tokenization - The preprocessor breaks the result into preprocessing tokens and whitespace. It replaces comments with whitespace.
- Macro Expansion and Directive Handling - Preprocessing directive lines, including file inclusion and conditional compilation, are executed. The preprocessor simultaneously expands macros and, in the 1999 version of the C standard, handles
_Pragmaoperators.
Examples
This section goes into some detail about C preprocessor usage. Good programming practice when writing C macros is crucial, particularly in a collaborative setting, so notes on this have been included. Of course, it is possible to abuse these features, but this is not recommended in a production environment.The most common use of the preprocessor is to include another file:
The preprocessor replaces the lineint main (void)
- include
#include <stdio.h> with the system header file of that name, which declares the printf() function amongst other things. More precisely, the entire text of the file 'stdio.h' replaces the #include directive.
This can also be written using double quotes, e.g. #include "stdio.h". The angle brackets were originally used to indicate 'system' include files, and double quotes user-written include files, and it is good practice to retain this distinction. C compilers and programming environments all have a facility which allows the programmer to define where include files can be found. This can be introduced through a command line flag, which can be parameterized using a makefile, so that a different set of include files can be swapped in for different operating systems, for instance.
Conventionally include files are given a .h extension, and files not included by others are given a .c extension. However, there is no requirement that this be observed. Occasionally you will see files with other extensions included from a .c file, in particular others with a .c extension.
The #ifdef, #ifndef, #else, #elif and #endif directives can be used for conditional compilation.
- define
- ifdef
- include
- else
- include
- endif
The first line defines a macro . The macro could instead be defined from the compiler's command line, perhaps to control compilation of the program from a makefile.
The subsequent code tests if a macro is defined. If it is, as in this example, the file <windows.h> is included, otherwise <unistd.h>.
Macro definition and expansion
There are two types of macros, object-like and function-like. Function-like macros take parameters; object-like macros don't. The generic syntax for declaring an identifier as a macro of each type is, respectively,
#defineWherever the identifier appears in the source code it is replaced with the replacement token list, which can be empty. For an identifier declared to be a function-like macro, it is only replaced when the following token is also a left parenthesis that begins the argument list of the macro invocation. The exact procedure followed for expansion of function-like macros with arguments is subtle.#define ( )
Object-like macros are conventionally used as part of good programming practice to create symbolic names for constants, e.g.
- define PI 3.14159
instead of hard-coding those numbers throughout one's code.
An example of a function-like macro is:
- define RADTODEG(x) ((x) * 57.29578)
This defines a radians to degrees conversion which can be written subsequently, e.g. RADTODEG(34). This is expanded in-place, so the caller does not need to litter copies of the multiplication constant all over his code. The macro here is written as all uppercase to emphasize that it is a macro, not a compiled function.
Note that the macro uses parentheses both around the argument and around the entire expression. Omitting either of these can lead to unexpected results. For example:
- Without parentheses around the argument:
- *Macro defined as #define RADTODEG(x) (x * 57.29578)
- *RADTODEG(a + b) expands to (a + b * 57.29578)
- Without parentheses around the whole expression:
Another example of a function-like macro is:
This macro illustrates one of the dangers of using function-like macros. One of the arguments, a or b, will be evaluated twice when this "function" is called. So, if the expression
- define MIN(a,b) ((a)>(b)?(b):(a))
MIN(++firstnum,secondnum) is evaluated, then firstnum may be incremented twice, not once as would be expected.
One of the most subtle and easy to abuse features of the C macropreprocessor is string concatenation. This is a feature of macrofunctions where two arguments can be 'glued' together using ## preprocessor operator. This allows two strings to be concatenated in the preprocessed code. This can be used to construct elaborate macros which act much like C++ templates (without many of their benefits).
For instance:
- define MYCASE(_item,_id) \
case _id: \ _item##_##_id=_id;\ break switch(x)
The line MYCASE(widget,23) gets expanded here into case 23: widget_23=23; break. (The semicolon after the right parentheses does not get expanded, but becomes the semicolon that completes the break statement.)
Note that the _ between the ## is 'literal' whereas the _id and _item arguments are 'arguments' to the function-style macro.
One stylistic note about this macro is that the semicolon on the last line of the macro definition is omitted so that the macro looks 'natural' when written. It could be included in the macro definition, but then there would be lines in the code without semicolons at the end which would throw off the casual reader.
The macro can be extended over as many lines as required using a backslash escape at the end of the line. The macro ends on the last line which does not end in a backslash.
Properly used, multi-line macros can greatly reduce the size and complexity of a C program and enhance its readability and maintainability.
Quoting the Macro Arguments
Although macro expansion does not occur within a quoted string, the text of the macro arguments can be quoted and treated as a string literal by using the "#" directive. For example, with the macrothe code
- define QUOTEME(x) #x
will expand toprintf("%s\n", QUOTEME(1+2));
This capability can be used with automatic string concatenation to make debugging macros. For example, the macro inprintf("%s\n", "1+2");
would print the name of an expression and its value, along with the file name and the line number.int some_function()
- define dumpme(x, fmt) printf("%s:%u: %s=" fmt, , , #x, x)
X-Macros
One little-known use pattern of the C preprocessor is known by the name X-Macros. X-Macros are the practice of using the #include directive multiple times on the same source header file, each time in a different environment of defined macros.
File: commands.x.h COMMAND(ADD, "Addition command") COMMAND(SUB, "Subtraction command") COMMAND(XOR, "Exclusive-or command")
typedef result_t (*command_handler_t)(state_t *);enum command_indices ;
command_handler_t command_handlers[] = ; char *command_descriptions[] = ;
The above allows for definition of new commands to consist of changing the command list in the X-Macro header file, and defining a new command handler of the proper name. The command descriptions list, handler list, and enumeration are updated automatically by the preprocessor.
User-defined compilation errors
The#error directive inserts an error message into the compiler output.
- error Gosh!
This prints Gosh! in the compiler output and halts the computation at that point. This is extremely useful if you aren't sure whether a given line is being compiled or not. It is also useful if you have a heavily parameterized body of code and want to make sure a particular #define has been introduced from the makefile, e.g.:
- ifdef WINDOWS
... /* windows specific code */elif defined(UNIX) ... /* unix specific code */
Compiler-specific preprocessor features
The#pragma directive is a compiler specific directive which compiler vendors may use for their own purposes. For instance, #pragmas are often used to allow suppression of specific error messages, manage heap and stack debugging, etc.Standard positioning macros
Certain symbols are predefined in ANSI C. Two useful ones are and , which expand into the current file and line number. For instance:
// debugging macros so we can pin down message provenance at a glance printf(WHERESTR ": hey, x=%d\n", WHEREARG, x);
- define WHERESTR "[file %s, line %d] "
- define WHEREARG ,
This prints the value of x, preceded by the file and line number, allowing quick access to which line the message was produced on. Note that the WHERESTR argument is concatenated with the following string.
External links
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
