Rob*_*rtS 0 c macros c-preprocessor
我想在我的 C 源代码中重新定义特定条件下宏常量的值。我无法使用条件预处理指令进行定义,LEN_OSG因为它是否用另一个值重新定义是在运行时决定的。
我已经拥有的是:
if(condition) // proof condition for replacing the value in LEN_OSG.
{
if(LEN_OSG != CBS_LEN) // check if LEN_OS already has the value in CBS_LEN.
{
#undef LEN_OSG // undefine macro LEN_OSG by using `#undef` directive.
#define LEN_OSG CBS_LEN // recreate the macro LEN_OSG with new value.
}
}
Run Code Online (Sandbox Code Playgroud)
C 语法是否允许另一种方法来缩写它,而不是使用该#undef指令,然后通过另一个#define指令(仅在一行中)使用新值重新创建宏?
所需的解决方案是这样的:
if(LEN_OSG != CBS_LEN) // check if LEN_OS already has the value in CBS_LEN.
{
#redefine LEN_OSG CBS_LEN // redefine LEN_OS with another value in one line.
}
Run Code Online (Sandbox Code Playgroud)
您的代码没有按预期工作。#define是在编译时执行的,所以你必须在编译时使用#if它。否则它总是被执行。
此外,没有#redefine,因此需要两个命令。
如果您有运行时条件,请使用普通变量并在运行时更改其值。