代码之家  ›  专栏  ›  技术社区  ›  highBandWidth

令牌“=”在预处理器表达式中无效[已关闭]

  •  5
  • highBandWidth  · 技术社区  · 14 年前

    我有一个程序:

    #include <iostream>
    
    #define _DEBUG = 1
    
    using namespace std;
    int main() {
            #if (_DEBUG == 1)
                    cout << "hello : " <<endl;
            #endif
    
            return 0;
    }
    

    编译它会出现错误:

    $ g++ a.cpp
    a.cpp:7:7: error: token "=" is not valid in preprocessor expressions
    $ g++ --version
    g++ (MacPorts gcc46 4.6.3_8) 4.6.3
    

    我想 == 等式是条件运算符吗?

    3 回复  |  直到 10 年前
        1
  •  10
  •   Mark Stevens    14 年前

    只是一个拼写错误,我想:

    #define _DEBUG = 1
    

    应该是

    #define _DEBUG 1
    

    我一直都这么做!

        2
  •  8
  •   James McNellis    14 年前
    #define _DEBUG = 1
    

    此声明 _DEBUG 作为扩展到的宏 = 1 ,所以当它在条件表达式中展开时

    #if (= 1 == 1)
    

    这显然不是有效的条件表达式。您需要删除 = 根据宏定义:

    #define _DEBUG 1
    

    此外,对于像这样的“标志”宏,通常最好测试宏是否定义,而不是宏的值。例如,

    #ifdef _DEBUG
    
        3
  •  3
  •   DanChianucci    14 年前

    应该是

    #define textToBeReplaced ReplacementText
    

    编译器将遍历所有代码,并将textToBeReplaced的所有实例替换为replacementText。

    如果是你的话

    #define _debug 1
    


    另一方面,你

        #if(_debug==1)
    

    应该 可能是

        #ifdef _debug
    

    注意到1在这里从未发挥作用吗?这意味着你实际上可以

        #define _debug
    

    并且不设置为任何内容