The C Preprocessor

4. Conditionals

  • 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.
  • e.g.
    • #ifdef
    • #ifndef
    • #endif
  • e.g.
    • #if (!defined(_DEBUG) && defined(USE_MYLIB))
    • #endif
    • 好處: 可同時檢測多個預編譯變數
  • e.g.
    • #if
    • #else
    • #endif
  • e.g.
    • #if
    • #elif
    • #elif
    • #else
    • #endif
  • Delete codes
    • #if 0
    • #endif

5. Diagnostics (診斷)

  • #error
    • The directive ‘#error’ causes the preprocessor to report a fatal error ( enforce the compiler stopping compile ). The tokens forming the rest of the line following ‘#error’ are used as the error message.
    • #ifdef  A
    • #error "ERROR A"
    • #endif
  • #warning
    • The directive ‘#warning’ is like ‘#error’, but causes the preprocessor to issue a warning and continue preprocessing. The tokens following ‘#warning’ are used as the warning message.

6. #line

  • The C preprocessor informs the C compiler of the location in your source code where each token came from.
  • e.g.
    • #line linenum
    • #line linenum filename
    • #line anything else

7. #pragma

  • The method specified by the C standard for providing additional information to the compiler.
  • e.g. #pragma token-sequence
    • If token-sequence exist, then doing the correspond action.

8. #ident


9.#using


10. Operator in preprocessor

  • #
    • stringizing operator
  • ##
    • token pasting operator
  • define()

11. Miscellaneous directive

  • #pragma
  • #line
  • #error

gcc 編譯過程


一個編譯過程通常需要4道程序
  1. 預處理 (Pre-Processing) 先處理那些#ifdef #define這些東西並做一些巨集代換
  2. 編譯 (Compiling) 做語意分析,翻譯成組合語言
  3. 彙編 (Assembling) 翻成機器碼與OS有關的格式,做成relocatable obj檔
  4. 鏈接 (Linking)  找到symbol(函式,變數名)與程式庫(shared obj)中的副程式 ,做成可執行obj檔(executable obj)

  • gcc -Wall -pedantic -ansi  (常用)



e.g.

Syntax

#define identifier replacement-list(optional)(1)
#define identifier( parameters ) replacement-list(2)
#define identifier( parameters, ... ) replacement-list(3)(since C99)
#define identifier( ... ) replacement-list(4)(since C99)
#undef identifier(5)

Explanation

#define directives

The #define directives define the identifier as a macro, that is they instruct the compiler to replace all successive occurrences of identifier with replacement-list, which can be optionally additionally processed. If the identifier is already defined as any type of macro, the program is ill-formed unless the definitions are identical.
Object-like macros
Object-like macros replace every occurrence of a defined identifier with replacement-list. Version (1) of the #definedirective behaves exactly like that.
Function-like macros
Function-like macros replace each occurrence of a defined identifier with replacement-list, additionally taking a number of arguments, which then replace corresponding occurrences of any of the parameters in the replacement-list. The number of arguments must be the same as the number of arguments in the macro definition (parameters) or the program is ill-formed. If the identifier is not in functional-notation, i.e. does not have parentheses after itself, it is not replaced at all.
Version (2) of the #define directive defines a simple function-like macro.
Version (3) of the #define directive defines a function-like macro with variable number of arguments. The additional arguments can be accessed using __VA_ARGS__ identifier, which is then replaced with arguments, supplied with the identifier to be replaced.
Version (4) of the #define directive defines a function-like macro with variable number of arguments, but no regular arguments. The arguments can be accessed only with __VA_ARGS__ identifier, which is then replaced with arguments, supplied with identifier to be replaced.

# and ## operators

In function-like macros, a # operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal. In addition, the preprocessor adds backslashes to escape the quotes surrounding embedded string literals, if any, and doubles the backslashes within the string as necessary. All leading and trailing whitespace is removed, and any sequence of whitespace in the middle of the text (but not inside embedded string literals) is collapsed to a single space. This operation is called "stringification". If the result of stringification is not a valid string literal, the behavior is undefined.
When # appears before __VA_ARGS__, the entire expanded __VA_ARGS__ is enclosed in quotes:
#define showlist(...) puts(#__VA_ARGS__)
showlist();            // expands to puts("")
showlist(1, "x", int); // expands to puts("1, \"x\", int")
(since C99)
## operator between any two successive identifiers in the replacement-list runs parameter replacement on the two identifiers and then concatenates the result. This operation is called "concatenation" or "token pasting". Only tokens that form a valid token together may be pasted: identifiers that form a longer identifier, digits that form a number, or operators + and = that form a +=. A comment cannot be created by pasting / and * because comments are removed from text before macro substitution is considered. If the result of concatenation is not a valid token, the behavior is undefined.
Note: some compilers offer an extension that allows ## to appear after a comma and before __VA_ARGS__, in which case the ## does nothing when __VA_ARGS__ is non-empty, but removes the comma when __VA_ARGS__ is empty: this makes it possible to define macros such as fprintf (stderr, format, ##__VA_ARGS__)



Macro offsetof


#include
#define offsetof(type, member) (size_t)&(((type*)0)->member)



Macro container_of


#include <linux/kernel.h>
#define container_of(ptr, type, member) ({ \
     const typeof( ((type *)0)->member ) *__mptr = (ptr); \
     (type *)( (char *)__mptr - offsetof(type,member) );})    


相關文件