简体   繁体   中英

Compilation error on the DEBUG identifier in Xcode

I am trying to build a static C++ library using Xcode. I get a build error on the DEBUG identifier in enum below, not sure why that is happening. I can compile it by using Clang++ from a terminal. Why does the compilation fail in Xcode?

Error:

Parse Issue
temp_1.h:9:5: Expected identifier

temp_1.h

enum LogLevel {

    DONT_PRINT = 0,
    SPEW       = 1,
    DEBUG     = 2,
    INFO       = 3,
    WARNING    = 4,
    ERROR      = 5,
    FATAL      = 6,
    INVALID                     = 7,
    NO_EXIT_ON_ERROR            = 8,
    MANDATORY                   = 9
};

class temp_1 {    
 public:
    temp_1();
    int get_var();
    void set_var(int _var);

 private:
    int var;    
};

temp_1.cpp:

#include "temp_1.h"

temp_1::temp_1() {        
    var = DEBUG;
}    
int temp_1::get_var() {
    return var;
}    
void temp_1::set_var(int _var) {    
    var = _var;
}

A lot of build environments define the preprocessor macro DEBUG when the code is compiled in debug mode, so that you can write

#ifdef DEBUG
// do something in debugging mode only
#endif

It looks like in your Xcode build, DEBUG is defined to something that isn't an identifier, perhaps DEBUG=1 or DEBUG= . Therefore your code after preprocessing looks like SPEW = 1, 1 = 2, or SPEW = 1, = 2, .

Avoid using the identifier DEBUG in your code. In C, you would typically put a prefix before these identifiers: LOG_LEVEL_DONT_PRINT , LOG_LEVEL_SPEW , LOG_LEVEL_DEBUG , etc. In C++, namespaces mostly make such prefixes unnecessary and undiomatic. Nonetheless, avoid all-uppercase DEBUG . You could name just this identifier differently, or use Spew , Debug , etc. and reserve all-caps to the preprocessor.

If you can't avoid using the identifier DEBUG , then you can allow the program to build by making sure that your build environment never defines it as a processor macro. If you want to have your cake and eat it, you can do better: ensure that either DEBUG is undefined or it is defined to DEBUG (ie nothing or -UDEBUG , or -DDEBUG=DEBUG on a compiler command line). When a preprocessor macro expands to itself, this passes the identifier unchanged to the next stage of the compiler (so DEBUG will act normally as an identifier), but blocks in a conditional compilation directive #ifdef DEBUG#endif will be compiled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM