c++libraries

Class and macro with same name from different libraries


In my project I am using 2 libraries. One defines a Status macro and the other has a class named Status in a namespace. This results in a conflict when using the class Status in my code:

// first library
namespace Test {
    class Status {};
}

// second library
#define Status int

// my code
int main() {
    Test::Status test;
    return 0;
}

Error:

error: expected unqualified-id before ‘int’
    8 | #define Status int

How can I use both libraries in my project?


Solution

  • If you do not need to use the Status macro defined by the 2nd library, then you can simply do the following :

    #include <second-library.h>
    #undef Status
    #include <first-library.h>
    

    If you want to be able to use the Status macro defined by the 2nd library, and the macro expands to a type, you can do the following:

    #include <second-library.h>
    using Status2 = Status;
    #undef Status
    #include <first-library.h>
    

    And then use it as Status2 instead of Status.

    If you want to be able to use the Status macro, but the macro expands to something other than a type, then I am afraid there is no easy solution: