Accessing the value of a Preprocessor Macro definition
Asked Answered
M

2

14

If I add a macro "FOO=bar" under GCC_PREPROCESSOR_DEFINITIONS (or Preprocessor Macros if you use XCode"), what would be the best way to access the value of "FOO"?

Currently, I use the clumsy:

    #define MACRO_NAME(f) #f
    #define MACRO_VALUE(f)  MACRO_NAME(f)

    #ifdef FOO
        NSLog(@"%s", MACRO_VALUE(FOO));
    #else
        NSLog(@"undefined");
    #endif

This will output "bar"

Surely, there must be a better/cleaner way?

Mohair answered 16/7, 2010 at 3:36 Comment(0)
O
10

What you are doing is the way to stringize (or stringify) macro values. The indirection is unavoidable.

This is mentioned in the GCC preprocessor manual section (archived link) that Rob linked to:

 #define xstr(s) str(s)
 #define str(s) #s
 #define foo 4
 str (foo)
      ==> "foo"
 xstr (foo)
      ==> xstr (4)
      ==> str (4)
      ==> "4
Odine answered 16/7, 2010 at 4:0 Comment(0)
A
2
NSLog(@"%s", #FOO);

See Stringification. It's the technique you're already using. What was wrong with it?

Alvarado answered 16/7, 2010 at 3:43 Comment(3)
This would result in NSLog(@"%s", #bar); after preprocessing - the indirection through another macro is needed to allow for macro expansion.Odine
It means you can't turn a preprocessor string macro into an NSString constant right? (Because as soon as you do [NSString stringWithFormat:macroString] it ceases to be a constant initializer.)Wegner
One of my projects had turned preprocessor string macros into NSString constant like this: #define kString "String" #define kNSString @kStringAlvarado

© 2022 - 2024 — McMap. All rights reserved.