next up previous contents
Next: 參數化巨集 Up: C 預處理器 Previous: 預定義巨集   Contents   DYWANG_HOME

預處理運算子

  1. Macro Continuation (\):延續巨集至第二行。
    #define message_for(a, b)  \
        printf(#a " and " #b ": We love you!\n")
    
  2. Stringize (#) :轉換巨集參數為字串
    1. 範例
      [dywang@dyw219 zzz]$ vim preprocess2.c
      [dywang@dyw219 zzz]$ cat preprocess2.c
      #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;
      }
      
    2. 編譯
      [dywang@dyw219 zzz]$ gcc -o preprocess2 preprocess2.c
      
    3. 執行結果
      [dywang@dyw219 zzz]$ ./preprocess2
      Carole and Debra: We love you!
      
  3. Token Pasting (##):組合兩個參數。
    1. 範例
      [dywang@dyw219 zzz]$ vim preprocess3.c
      [dywang@dyw219 zzz]$ cat preprocess3.c
      #include <stdio.h>
      
      #define tokenpaster(n) printf ("token" #n " = %d\n", token##n)
      
      int main(void) {
      	int token34 = 40;
      
      	tokenpaster(34);
      	return 0;
      }
      
    2. 編譯
      [dywang@dyw219 zzz]$ gcc -o preprocess3 preprocess3.c
      
    3. 執行結果
      [dywang@dyw219 zzz]$ ./preprocess3
      token34 = 40
      
  4. defined():回傳括號內的表示式是否被定義。
    1. 範例
      [dywang@dyw219 zzz]$ vim preprocess4.c
      [dywang@dyw219 zzz]$ cat preprocess4.c
      #include <stdio.h>
      
      #if !defined (MESSAGE)
      	#define MESSAGE "You wish!"
      #endif
      
      int main(void) {
      	printf("Here is the message: %s\n", MESSAGE);  
      	return 0;
      }
      
    2. 編譯
      [dywang@dyw219 zzz]$ gcc -o preprocess4 preprocess4.c
      
    3. 執行結果
      [dywang@dyw219 zzz]$ ./preprocess4
      Here is the message: You wish!
      



De-Yu Wang 2021-01-11