Define Macro on Command Line

- - | Comments

之前曾經遇過在source file與header file裡找不到Macro定義的狀況, 最後才發現Macro被定義在command line上, 以下示範如何在command line上定義Macro.

範例程式:

test.c
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main(void)
{
 int a = 1 ;
 int b = 2 ;
 int c ;
 c = SUM(a,b);
 printf("c = %d\n",c);
 return 0 ;
}

編譯與執行:

Terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
bramante@matrix:~/blog/define_macro_on_command_line$ gcc -o ./test "-DSUM(a,b)=(a+b)" ./test.c
bramante@matrix:~/blog/define_macro_on_command_line$ ./test
c = 3
bramante@matrix:~/blog/define_macro_on_command_line$ gcc -E "-DSUM(a,b)=(a+b)" ./test.c | grep -A8 "int main(void)"
int main(void)
{
 int a = 1 ;
 int b = 2 ;
 int c ;
 c = (a+b);
 printf("c = %d\n",c);
 return 0 ;
}
bramante@matrix:~/blog/define_macro_on_command_line$

從執行的結果, 與展開Macro後的source code, 可以確定在command line上定義Macro是可行的.

Comments