#include <iostream>
#define MY_MACRO "hello"
int main() {
#if MY_MACRO == "asdasd"
std::cout << "The macro is not equal to hello" << std::endl;
#else
std::cout << "The macro is equal to hello" << std::endl;
#endif
return 0;
}
In this form it would not compile successfully.
#include <iostream>
#define MY_MACRO hello
int main() {
#if MY_MACRO == asdasd
std::cout << "The macro is not equal to hello" << std::endl;
#else
std::cout << "The macro is equal to hello" << std::endl;
#endif
return 0;
}
And in this form #if MY_MACRO == XXX would always judge as true.
So how to compare strings when pre-complie?
You have two options:
Use numbers instead of strings, and give them names using macros:
Don't use preprocessor, use a plain
if(orif constexpr, the only difference here is that the latter forces the condition to be a compile-time constant). This means that all branches have to be valid (have to compile) regardless of which one is choosen:Or make
MY_MACROa globalconstexpr std::string_viewvariable if you don't need to override it with compiler flags.