在c中测试标识符的特定值

时间:2014-04-30 10:30:44

标签: c

#define CPU Mntel_i7 

void main(){
    #if CPU == Intel_i7
        printf("Performance should be good.\n" );
    #endif
    getchar();
}

我将CPU定义为Mntel_i7,当我测试它是否为Intel_i7时,它包含#if #endif块中的代码并将其打印到屏幕 怎么可能?

2 个答案:

答案 0 :(得分:1)

在您的情况下,以下声明

#if CPU == Intel_i7

将扩展为

#if Mntel_i7 == Intel_i7

由于Mntel_i7Intel_i7都不是宏,cpp会将它们视为零,这意味着上述条件等于

#if 0 == 0

将是真的。

通常,您可以通过类似的方式实现目标

#if CPU_Intel_i7
    /* If is Intel i7 */
#endif

使用编译器选项-DCPU_Intel_i7编译该源文件,或在其他位置定义该宏。

答案 1 :(得分:0)

您可以对预定义的宏进行比较...您定义的标识符Intel_i7Mntel_i7没有正确的值。

或者你可以通过给标识符赋予一些价值来做到这一点......

#define Mntel_i7 1
#define Intel_i7 2

#define CPU Mntel_i7 

int main(void)
{
#if CPU == Intel_i7
    printf("Performance should be good.\n");
#endif

    return 0;
}