0

I want to use a macro to define another macro in C++. Were the macro to define the macro has two arguments, one the name of a macro to do an "#ifdef" test on, the other the name of the new macro to #define. This example is pared down. The real situation is complicated which is why I want to factor it out.

#define TEST_ME // or NOT 


#define DEFINE_A_MACRO( _test_me_, _define_me_ )    \
                                                    \
    #ifdef (actual value of)_test_me_                 \
         #define (actual value of _define_me_) One Thing \
    #else                                                  \
         #define (actual value of _define_me_) Another Thing \
    #endif 

 ...

  DEFINE_A_MACRO( TEST_ME, DEFINE_ME )

Is there any way to do this ? I doubt it but might as well pose the question :)

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
peterk
  • 5,136
  • 6
  • 33
  • 47
  • A macro expansion cannot contain preprocessor directives. – Chris Dodd Dec 11 '17 at 02:42
  • Escaping a # symbol in a #define macro? is not the same question it answers "Yes" to you can escape hash symbols in a macro BUT it ALSO answers this question as one of the responses says it will not "rescan" the macro contents and apply and now expanded preprocessor directives. To this question the answer is NO - the way this is worded likely good to have in the search. – peterk Dec 19 '17 at 15:51

1 Answers1

1

No. while the preprocessor can support multiple levels of token replacement (one macro may reference another), this only applies to tokens. You can't generate new preprocessor directives.

In other words, you solve this by

#ifdef TEST_ME
  #define THING ONETHING
#else
  #define THING ANOTHERTHING
#endif
#define DEFINE_ME THING

(Or by writing C++ code - macro's are really unnecessary these days)

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • They are often needed for defining platform specific code for different versions of libraries with common source. and the nasty bit microsoft has with having to declare items dllimport dll export or not depeding on the linkage and build type – peterk Dec 12 '17 at 06:12
  • I have selected this as an answer even though I would like it to be possible but NO is a valid answer. – peterk Dec 12 '17 at 06:13