在编译时为变量赋值

Igg*_*ggY 2 c c++ gcc

我想在编译代码时为变量分配一个特定的值(对于C和C++):

例如:

//test.c
int main()
{
   int x = MYTRICK ; (edit: changed __MYTRICK__ to MYTRICK to follow advices in comment)
   printf ("%d\n", x);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

能够做类似的事情:

gcc -XXX MYTRICK=44 test.c -o test
Run Code Online (Sandbox Code Playgroud)

结果如下:

$./test
44
Run Code Online (Sandbox Code Playgroud)

oua*_*uah 7

使用-D选项:

gcc -DMYTRICK=44 test.c -o test
Run Code Online (Sandbox Code Playgroud)

MYTRICK在程序中使用宏而不是__MYTRICK__.开头的名称__由实现保留.