4

我想在我的代码编译时为变量分配一个特定的值(对于 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;
}

能够做类似的事情:

gcc -XXX MYTRICK=44 test.c -o test

结果是:

$./test
44
4

1 回答 1

9

使用-D选项:

gcc -DMYTRICK=44 test.c -o test

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

于 2012-09-26T09:12:38.540 回答