How do you test if two #defines are the same with the C preprocessor

c, c-preprocessor

Solution

You cannot compare the preprocessor macros as strings. One possibility would be to put the hardware port address (e.g., via another macro in the platform-specific headers) into the `#define`s and then compare the addresses.

However, the easiest way might be to do the comparison of addresses in actual code, e.g.:

if (&FOO_PORT == &BAR_PORT) {
    // populate callbacks with handle_foo_bar_func
} else {
    // populate callbacks with handle_foo_func and handle_bar_func
}

While not done in pre-processor, the compiler may be able to optimise away the unused branch since the hardware addresses are likely compile-time constants.

Problem

I have a C program which has platform-specific defines for access to low-level hardware. On some platforms, two macros point to the same variable, on others they are different: ``` //Platform_One.h #define FOO_PORT (io.portA) #define BAR_PORT (io.portB) //Platform_Two.h #define FOO_PORT (io.portC) #define BAR_PORT (io.portC) //same ``` I have some initializer code that is different based on whether the #defines are the same or not. Conceptually, I'd like code like this: ``` callback_struct_t callbacks[] = { #if FOO_PORT == BAR_PORT //unfortunately invalid {&FOO_PORT, handle_foo_bar_func}, #else {&FOO_PORT, handle_foo_func}, {&BAR_PORT, handle_bar_func}, #endif {0,0} }; ``` Is there a reliable way to test at compile time if two arbitrary macros have the same definition?

Original source

Related problems