1

Possible Duplicate:
C Preprocessor, Stringify the result of a macro

I have this define:

#define VERSION 0.3.2

I want to convert this to @"0.3.2" (an NSString) -- is it possible? Presume that I am not allowed to add quotation marks to the #define.

Something like this, but presumably with an extra step:

NSString *myVersion = [NSString stringWith???:VERSION];
Community
  • 1
  • 1
Ben Flynn
  • 18,524
  • 20
  • 97
  • 142
  • There's a way to do it, but it takes some macro magic that I always have to Google for. – Hot Licks Jul 19 '12 at 00:09
  • I agree with @robmayoff -- my Q is a dup. I appreciate the help! – Ben Flynn Jul 19 '12 at 00:19
  • Does the version number you're #defining happen to be the version number of your application (the one in your XCode Target settings)? If so, you can retrieve it programmatically using `[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]`. This returns a string. To compare two version number strings, call `[versionString1 compare:versionString2 options:NSNumericSearch]`. If you're storing some other version number, disregard. – Cowirrie Jul 19 '12 at 06:57
  • Our authoritative version is in a define, unfortunately. – Ben Flynn Jul 19 '12 at 16:29

2 Answers2

2

As in the possible dup I linked, you need two more levels of macros because you want to stringify a macro expansion:

#define VERSION 0.3.2
#define StringifyWithoutExpandingMacros(x) #x
#define Stringify(x) StringifyWithoutExpandingMacros(x)

NSLog(@"VERSION = %@", @StringifyWithoutExpandingMacros(VERSION));
// output: VERSION = VERSION

NSLog(@"VERSION = %@", @Stringify(VERSION));
// output: VERSION = 0.3.2

Note that you can just stick an @ in front of the macro invocation. It doesn't need to be inside the macro. You can put it in the macro if you want, though:

#define NSStringifyWithoutExpandingMacros(x) @#x
#define NSStringify(x) NSStringifyWithoutExpandingMacros(x)

NSLog(@"VERSION = %@", NSStringify(VERSION));
// output: VERSION = 0.3.2
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

Stringify!

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)

@HotLick's Macro magic at it's finest.

CodaFi
  • 43,043
  • 8
  • 107
  • 153