在编译时为变量赋值

Assign a value to a variable at compilation time

本文关键字:变量 赋值 编译      更新时间:2023-10-16
我想

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

例如:

//test.c
int main()
{
   int x = MYTRICK ; (edit: changed __MYTRICK__ to MYTRICK to follow advices in comment)
   printf ("%dn", x);
   return 0;
}

比林能够做这样的事情:

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

并因此:

$./test
44

使用-D选项:

gcc -DMYTRICK=44 test.c -o test

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