I want to create a macro that is fully executed at compile time (not runtime). If two values are both defined, then I want to check if they are equal. If at least one of them is not defined, then nothing should happen. I have come halfway, the following works great:
#define VALIDATE_ADDR(ADDR1,ADDR2) _Static_assert(ADDR1 == ADDR2, #ADDR1 " is not equal to " #ADDR2);
However, when I try to nest that macro into another macro, then I run into trouble:
Can someone please help me so I can do checks like this:
#define MY_ADDR_1 (1)
#define MY_ADDR_2 (2)
#define MY_ADDR_3 (3)
VALIDATE_ADDR_IF_THEY_BOTH_EXIST(MY_ADDR_1, MY_ADDR_2); // Compile time error since MY_ADDR_1 != MY_ADDR_2
VALIDATE_ADDR_IF_THEY_BOTH_EXIST(MY_ADDR_3, MY_ADDR_4); // Compiles just fine since MY_ADDR_4 is not defined
AFAIK, that's not possible, since the # token is reserved for stringifying macro parameters within the macro expansion.
Also, I see that your definition for VALIDATE_ADDR ends in a semicolon. In general, you do not want to end a macro with a semicolon, since this can lead to, in the best case, a compiler error, and in the worst case, a subtle and hard to find bug.
What do you mean? I've clearly stated I want compile time execution, not runtime execution of this macro. Are you thinking of the _Static_assert function? It is executed at compile time, I think it's a feature built into the gcc compiler.
I have never learn C, just c++ ... and this code where I am working on is written for Linux, and for other compilers than VS. That is why I got tones of errors, one of them I don't know how to handle them without broke the functionality (I cannot try what I modify, so I am working blind).