C preprocessor

The C preprocessor is a preprocessor for the C programming language.

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.

Contents

Phase 1: Trigraph Replacement

The preprocessor replaces trigraph sequences with the characters they represent.

Phase 2: Line Splicing

Physical source lines that are continued with escaped newline sequences are spliced to form logical lines.

Phase 3: Tokenization

The preprocessor breaks the result into preprocessing tokens and whitespace. It replaces comments with whitespace.

Phase 4: 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 _Pragma operators.

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:

#include <stdio.h>

int main (void)
{
    printf("Hello, world!\n");
    return 0;
}

The preprocessor replaces the line #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.

It is good programming practice to use the compiler parameter to define the include file paths. It is not good programming practice to used relative or absolute file names in #includes. If your source is copied to another system with a different directory structure, this could 'break' your code, requiring numerous edits to get it to compile on the new system.

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 __WINDOWS__

#ifdef __WINDOWS__
#include <windows.h>
#else
#include <unistd.h>
#endif

The first line defines a macro __WINDOWS__. 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 __WINDOWS__ 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,

 #define <identifier> <replacement token list>
 #define <identifier>(<parameter list>) <replacement token list>

Wherever 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.

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.295736)

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.

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) {
      MYCASE(widget,23);
  }

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 case 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.

One drawback of multi-line macros is that comments cannot be written in the macro definition in standard C. Hence line-by-line source documentation can't be written in the body of the macro. However, properly used, multi-line macros can greatly conflate the size and complexity of a C program and enhance its readability and maintainability.

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 UNIX
    ... /* unix specific code */
#else
    #error "Unknown operating system"
#endif

Then there is the #pragma directive. This is a compiler specific directive which each vendor uses for whatever purpose they wish. For instance, #pragmas are used to allow suppression of specific error messages, manage heap and stack debugging, and so on.

Certain symbols are predefined in ANSI C. Two useful ones are __FILE__ and __LINE__, which expand into the current file and line number. For instance:

// debugging macros so we can pin down message provenance at a glance
#define WHERESTR "[file %s, line %d] "
#define WHEREARG __FILE__,__LINE__

printf(WHERESTR ": hey, x=%d\n", WHEREARG, x);

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.tr:C önişlemcisi

Navigation

  • Art and Cultures
    • Art (https://academickids.com/encyclopedia/index.php/Art)
    • Architecture (https://academickids.com/encyclopedia/index.php/Architecture)
    • Cultures (https://www.academickids.com/encyclopedia/index.php/Cultures)
    • Music (https://www.academickids.com/encyclopedia/index.php/Music)
    • Musical Instruments (http://academickids.com/encyclopedia/index.php/List_of_musical_instruments)
  • Biographies (http://www.academickids.com/encyclopedia/index.php/Biographies)
  • Clipart (http://www.academickids.com/encyclopedia/index.php/Clipart)
  • Geography (http://www.academickids.com/encyclopedia/index.php/Geography)
    • Countries of the World (http://www.academickids.com/encyclopedia/index.php/Countries)
    • Maps (http://www.academickids.com/encyclopedia/index.php/Maps)
    • Flags (http://www.academickids.com/encyclopedia/index.php/Flags)
    • Continents (http://www.academickids.com/encyclopedia/index.php/Continents)
  • History (http://www.academickids.com/encyclopedia/index.php/History)
    • Ancient Civilizations (http://www.academickids.com/encyclopedia/index.php/Ancient_Civilizations)
    • Industrial Revolution (http://www.academickids.com/encyclopedia/index.php/Industrial_Revolution)
    • Middle Ages (http://www.academickids.com/encyclopedia/index.php/Middle_Ages)
    • Prehistory (http://www.academickids.com/encyclopedia/index.php/Prehistory)
    • Renaissance (http://www.academickids.com/encyclopedia/index.php/Renaissance)
    • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
    • United States (http://www.academickids.com/encyclopedia/index.php/United_States)
    • Wars (http://www.academickids.com/encyclopedia/index.php/Wars)
    • World History (http://www.academickids.com/encyclopedia/index.php/History_of_the_world)
  • Human Body (http://www.academickids.com/encyclopedia/index.php/Human_Body)
  • Mathematics (http://www.academickids.com/encyclopedia/index.php/Mathematics)
  • Reference (http://www.academickids.com/encyclopedia/index.php/Reference)
  • Science (http://www.academickids.com/encyclopedia/index.php/Science)
    • Animals (http://www.academickids.com/encyclopedia/index.php/Animals)
    • Aviation (http://www.academickids.com/encyclopedia/index.php/Aviation)
    • Dinosaurs (http://www.academickids.com/encyclopedia/index.php/Dinosaurs)
    • Earth (http://www.academickids.com/encyclopedia/index.php/Earth)
    • Inventions (http://www.academickids.com/encyclopedia/index.php/Inventions)
    • Physical Science (http://www.academickids.com/encyclopedia/index.php/Physical_Science)
    • Plants (http://www.academickids.com/encyclopedia/index.php/Plants)
    • Scientists (http://www.academickids.com/encyclopedia/index.php/Scientists)
  • Social Studies (http://www.academickids.com/encyclopedia/index.php/Social_Studies)
    • Anthropology (http://www.academickids.com/encyclopedia/index.php/Anthropology)
    • Economics (http://www.academickids.com/encyclopedia/index.php/Economics)
    • Government (http://www.academickids.com/encyclopedia/index.php/Government)
    • Religion (http://www.academickids.com/encyclopedia/index.php/Religion)
    • Holidays (http://www.academickids.com/encyclopedia/index.php/Holidays)
  • Space and Astronomy
    • Solar System (http://www.academickids.com/encyclopedia/index.php/Solar_System)
    • Planets (http://www.academickids.com/encyclopedia/index.php/Planets)
  • Sports (http://www.academickids.com/encyclopedia/index.php/Sports)
  • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
  • Weather (http://www.academickids.com/encyclopedia/index.php/Weather)
  • US States (http://www.academickids.com/encyclopedia/index.php/US_States)

Information

  • Home Page (http://academickids.com/encyclopedia/index.php)
  • Contact Us (http://www.academickids.com/encyclopedia/index.php/Contactus)

  • Clip Art (http://classroomclipart.com)
Toolbox
Personal tools