Search code examples
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:

    • You could look at the definition of the macro and rewrite it with a different name, although this might get you into trouble if, in a future version of the library, they change the definition.

    • You might wrap the library with the macro into a library of your own, so that you can define everything you want with names that you choose, though this might be more work than you bargained for.