Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Preprocessor

C Preprocessor

C Preprocessor (CPP)is an independent stage in the compilation process; beforeactual compilationit performs text processing on the source code. Its main functions include:

C PreprocessorIt is not part of the compiler, but it is a separate step in the compilation process.

In short, the C preprocessor is just a text replacement tool; it instructs the compiler to perform the required preprocessing before actual compilation.

We will abbreviate the C Preprocessor as CPP.

All preprocessor commands begin with a hash sign #. It must be the first non-blank character; for readability, preprocessor directives should start from the first column.

All important preprocessor directives are listed below:

Instruction Description Usage examples
#define Define a macro (symbolic constant or function-like macro) #define PI 3.14159
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#include Including the header #include
#include "myheader.h"
#undef Undefine a defined macro #undef PI
#ifdef Compile the following code if the macro is defined #ifdef DEBUG
 `printf("Debug info\n");`       

 `#endif` |

| #ifndef | Compile the following code if the macro is not defined (commonly used for include guards) | #ifndef HEADER_H
#define HEADER_H
/* 内容 */
#endif | | #if | Conditional compilation (can be used with the defined operator) | #if VERSION > 2
/* 新版代码 */
#endif | | #else | #if/#ifdef/#ifndefalternative branch #ifdef WIN32
/* Windows代码 */
#else
/* 其他系统 */
#endif | | #elif | Similar to else if | #if defined(UNIX)
/* Unix代码 */
#elif defined(WIN32)
/* Windows代码 */
#endif | | #endif | End a conditional compilation block | As shown in the example above | | #error | Generate a compilation error and output a message #if !defined(C99)
#error "需要C99标准"
#endif | | #pragma | Compiler-specific directive (non-standard, varies by compiler) #pragma once
#pragma pack(1) |

Preprocessor examples

Analyze the following examples to understand the different directives.



#define MAX_ARRAY_LENGTH 20

This directive tells CPP to define all MAX_ARRAY_LENGTH as 20. Use #define to define constants to improve readability.



#include 

#include "myheader.h"

These directives tell CPP to get stdio.h from thesystem libraryand add the text to the current source file. The next line tells CPP to get myheader.hfrom the local directory, and add its content to the current source file.



#undef  FILE_SIZE

#define FILE_SIZE 42

This directive tells CPP to undefine the already defined FILE_SIZE and define it as 42.



#ifndef MESSAGE

   #define MESSAGE "You wish!"

#endif

This directive tells CPP to define MESSAGE only when MESSAGE is not defined.



#ifdef DEBUG

   /* Your debugging statements here */

#endif

This directive tells CPP to process the statements if DEBUG is defined. When compiling, if you pass the -DDEBUG switch to the gcc compiler, this directive is very useful. It defines DEBUG, and you can turn debugging on or off at any time during compilation.

Example

#include

// Define a constant macro

#define PI 3.1415926

#define GREETING "Hello, World!"

// Define a function-like macro (note the use of parentheses)

#define SQUARE(x) ((x) * (x))

#define MAX(a, b) ((a) > (b) ? (a) : (b))

// Conditional compilation example

#define DEBUG 1

int

main

(

)

{

   

// Use the constant macro

   

printf

(

"Value of PI: %f\n"

,

PI

)

;

   

printf

(

"%s\n"

,

GREETING

)

;

   

   

// Use the function-like macro

   

int

x

=

5

;

   

printf

(

"The square of %d is: %d\n"

,

x

,

SQUARE

(

x

)

)

;

   

printf

(

"The larger of 3 and 5 is: %d\n"

,

MAX

(

3

,

5

)

)

;

   

   

// Conditional compilation example

   

#ifdef DEBUG

   

printf

(

"[Debug info] Program reached the main function\n"

)

;

   

#endif

   

   

// Compiler version check

   

#if STDC_VERSION >= 201112L

   

printf

(

"Using the C11 standard\n"

)

;

   

#elif STDC_VERSION >= 199901L

   

printf

(

"Using the C99 standard\n"

)

;

   

#else

   

printf

(

"Using the C89/C90 standard\n"

)

;

   

#endif

   

   

// Error directive example (uncommenting will cause a compilation error)

   

// #error "This is a manually triggered error"

   

   

return

0

;

}

Best Practice Recommendations

  1. Macro naming:

  2. Name macros using all uppercase letters and underscores
  3. Example:#define MAX_SIZE 100
  4. - Name macros using all uppercase letters and underscores - example: `#define MAX_SIZE 100`
    1. Notes on function-like macros:

    2. Enclose each parameter and the entire expression in parentheses
    3. Avoid using arguments with side effects (such asSQUARE(x++))
    4. - Enclose each parameter and the entire expression in parentheses - avoid using arguments with side effects (such as `SQUARE(x++)`)
      1. Header Guards:

        #ifndef MY_HEADER_H
        
        

      #define MY_HEADER_H /* header file content */ #endif 4.

      Conditional compilation debugging:

      #ifdef DEBUG
      
      #define DEBUG_PRINT(fmt, ...) printf(fmt, ##VA_ARGS)
      
      #else
      
      #define DEBUG_PRINT(fmt, ...)
      
      #endif
      
      
      5.

      Cross-platform Development:

      #if defined(_WIN32)
      
      // Windows specific code
      
      #elif defined(linux)
      
      // Linux specific code
      
      #elif defined(APPLE)
      
      // macOS specific code
      
      #endif
      
      

      Predefined macros

      ANSI C defines many macros. You can use these macros in programming, but you cannot directly modify these predefined macros.

      macro Description
      DATE The current date, a character constant in the format "MMM DD YYYY".
      TIME The current time, a character constant in the format "HH:MM:SS".
      FILE This contains the current file name, a string constant.
      LINE This contains the current line number, a decimal constant.
      STDC It is defined as 1 when the compiler compiles with the ANSI standard.

      Let's try the following example:

      Example

      #include

      <
      
      stdio.h
      
      /*
      
      */
      
      int
      
      main
      
      (
      
      )
      
      {

      // Print the current source file name (string constant)

      printf

      (

      "

      Current file: %s

      \

      n

      "

      ,

      FILE

      )

      ;

      // Print the compilation date (in "MMM DD YYYY" format)

      printf

      (

      "

      Compilation date: %s

      \

      n

      "

      ,

      DATE

      )

      ;

      // Print the compilation time (in "HH:MM:SS" format)

      printf

      (

      "

      Compilation time: %s

      \

      n

      "

      ,

      TIME

      )

      ;

      // Print the current line number (decimal integer)

      printf

      (

      "

      Current line number: %d

      \

      n

      "

      ,

      LINE

      )

      ;

      // Check whether it conforms to the ANSI/ISO standard (1 means yes)

      printf

      (

      "

      ANSI standard: %d

      \

      n

      "

      ,

      STDC

      )

      ;

      // Practical example: debug information output

      printf

      (

      "

      \

      n[Debug info] %s (line %d) compiled on %s %s

      \

      n

      "

      ,

      FILE

      ,

      LINE

      ,

      DATE

      ,

      TIME

      )

      ;

      return

      0

      ;

      }

      When the above code (in the file test.c ) is compiled and executed, it produces the following result:

      
      
      当前文件: predef_macros.c
      
      编译日期: Jul 5 2023
      
      编译时间: 14:30:45
      
      当前行号: 13
      
      ANSI标准: 1
      
      
      
      [调试信息] predef_macros.c (第16行) 编译于 Jul 5 2023 14:30:45
      
      

      Preprocessor operators

      The C preprocessor provides the following operators to help you create macros:

      Macro continuation operator (\)

      A macro is usually written on a single line. However, if a macro is too long to fit on one line, the macro continuation operator (\) is used. For example:

      
      
      #define  message_for(a, b)  \
      
          printf(#a " and " #b ": We love you!\n")
      
      
      
      
      Stringizing operator (#)

      In a macro definition, when you need to convert a macro's argument into a string constant, the stringizing operator (#) is used. This operator used in a macro has a specific argument or argument list. For example:

      Example

      #include

      <
      
      stdio.h
      
      #define
      
      message_for
      
      (
      
      a
      
      ,
      
      b
      
      )
      
      \
      
      printf
      
      (
      
      a
      
      "
      
      and
      
      "
      
      b
      
      "

      : We love you!

      \

      n

      "

      )

      int

      main

      (

      void

      )

      {

      message_for

      (

      Carole

      ,

      Debra

      )

      ;

      return

      0

      ;

      }

      When the code above is compiled and executed, it produces the following result:

      
      
      Carole and Debra: We love you!
      
      

      Token pasting operator (##)

      The token pasting operator (##) within a macro definition combines two arguments. It allows two separate tokens in a macro definition to be merged into one token. For example:

      Example

      #include

      <
      
      stdio.h
      
      #define
      
      tokenpaster
      
      (
      
      n
      
      )
      
      printf
      
      (
      
      "
      
      token
      
      "
      
      n
      
      "

      = %d

      "

      ,

      token

      n

      )

      int

      main

      (

      void

      )

      {

      int

      token34

      =

      40

      ;

      tokenpaster

      (

      34

      )

      ;

      return

      0

      ;

      }

      When the code above is compiled and executed, it produces the following result:

      
      
      token34 = 40
      
      

      How does this happen? Because this example produces the following actual output from the compiler:

      
      
      printf ("token34 = %d", token34);
      
      

      This example demonstrates that token##n is concatenated into token34; here, we have usedStringizing operator (#)andToken pasting operator (##).

      the defined() operator

      Preprocessor defined operator is used in constant expressions to determine whether an identifier has been defined using #define. If the specified identifier is defined, the value is true (non-zero). If the specified identifier is not defined, the value is false (zero). The following example demonstrates the use of the defined() operator:

      Example

      #include

      <
      
      stdio.h
      
      #if

      !

      defined

      (

      MESSAGE

      )

      #define

      MESSAGE

      "

      You wish!

      "

      #endif

      int

      main

      (

      void

      )

      {

      printf

      (

      "

      Here is the message: %s

      \

      n

      "

      ,

      MESSAGE

      )

      ;

      return

      0

      ;

      }

      When the code above is compiled and executed, it produces the following result:

      
      
      Here is the message: You wish!
      
      

      Parameterized macros

      A powerful feature of CPP is the ability to use parameterized macros to simulate functions. For example, the following code calculates the square of a number:

      
      
      int square(int x) {
      
         return x * x;
      
      }
      
      

      We can rewrite the above code using a macro, as follows:

      
      
      #define square(x) ((x) * (x))
      
      

      Before using a macro with parameters, you must use the #define #define directive to define it. The parameter list is enclosed in parentheses and must immediately follow the macro name. No space is allowed between the macro name and the left parenthesis. For example:

      Example

      #include

      <
      
      stdio.h
      
      #define
      
      MAX
      
      (
      
      x
      
      ,
      
      y
      
      )
      
      (
      
      (
      
      x
      
      )
      
      (
      
      y
      
      )
      
      ?
      
      (
      
      x
      
      )

      :

      (

      y

      )

      )

      int

      main

      (

      void

      )

      {

      printf

      (

      "

      Max between 20 and 10 is %d

      \

      n

      "

      ,

      MAX

      (

      10

      ,

      20

      )

      )

      ;

      return

      0

      ;

      }

      When the code above is compiled and executed, it produces the following result:

      
      
      Max between 20 and 10 is 20