Is there a way to check the non-numeric value of a macro

Let's pretend that

#define Name Joe 

Is there a way to distinguish between different values ​​for a macro. The following don't work, but you get the idea

 #if Name==Joe // some code #elif Name==Ben // some alternative code #endif 

I want to use this to create various object files from one source code. The source is a little different, so it can be easily controlled with macros. The macro must be passed using the compiler flag -DName=Joe . Also note that Name will be the actual name of the symbol, so we won’t be able to use tricks based on #define Joe 1 , etc.


forced editing Please note that this similar question really deals with string characters. Moreover, the answers there do not help. The accepted answer avoids the problem (but does not solve it), another answer uses strcmp in macros that rely on the extension, etc.

+7
macros c-preprocessor preprocessor-directive
source share
2 answers

Yes, it is possible, but it’s not all so beautiful.

Here is an example; change NAME and type the correct thing. You just need to define TEST_FOR_Name ahead of time for each name, providing each with a unique value.

 #define TEST_FOR_Joe 1 #define TEST_FOR_Ben 2 #define DO_TEST(NAME1, NAME2) DO_TEST_impl(NAME1, NAME2) #define DO_TEST_impl(NAME1, NAME2) TEST_FOR_ ## NAME1 == TEST_FOR_ ## NAME2 #define NAME Ben #include <iostream> int main() { std::cout << "Hello!" << std::endl; #if DO_TEST(NAME, Joe) std::cout << "Joe Found!" << std::endl; #elif DO_TEST(NAME, Ben) std::cout << "Ben Found!" << std::endl; #else std::cout << "Neither found!" << std::endl; #endif } 

The basic idea is that we create markers with unique numerical values ​​associated with each name. If it cannot find the value for the token, the comparison simply fails, but otherwise it ensures that the numbers are the same.

+12
source share

Pretty sure that you will find that you cannot use only C ++, there are some ways to expand the set of elements that people have found, but this is not portable. Another user asks something like this: Here

-one
source share

All Articles