5

There's got to be a way to do this...

I have a header file, version.h with one line...

#define VERSION 9

and a few files use the defined value of VERSION as an integer. That's fine.

Without changing the way VERSION is defined, I need to build an initialized "what" string that contains that value, so I need something like this...

char *whatversion = "@(#)VERSION: " VERSION;

obviously this doesn't compile, so somehow I need to get a string of the preprocessed value of VERSION essentially giving this...

char *whatversion = "@(#)VERSION: " "9";

Any ideas? Is this possible?

osgx
  • 90,338
  • 53
  • 357
  • 513
Ed.
  • 928
  • 1
  • 10
  • 23

2 Answers2

5

It is not a datatype, it is a token. A blob of text.

K & R talk about concatenating values:

 The preprocessor operator ## provides a way to concatenate actual arguments
 during macro expansion. If a parameter in the replacement text is adjacent
 to a ##, the parameter is replaced by the actual argument, the ## and
 surrounding white space are removed, and the result is re-scanned. For example,
 the macro paste concatenates its two arguments:

    #define paste(front, back) front ## back

    so paste(name, 1) creates the token name1.

-- try that. #define the string before you get to char *version=

Aubin
  • 14,617
  • 9
  • 61
  • 84
jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
  • You can only paste tokens together, which is pretty limiting. You cannot easily generate a string, for example, and `#(@)VERSION` is *not* a token, so it cannot be concatenated with anything. (`"#(@)VERSION"` is a token, but you cannot concatenate a string token to another token, unless that token is a length indicator. Fortunately, you don't need to concatenate string tokens.) – rici Mar 06 '13 at 00:14
0

Inside a macro, you can use the "stringify" operator (#) which will do exactly what you want:

#define STR2(x) #x
#define STR(x) STR2(x)
#define STRING_VERSION STR(VERSION)

#define VERSION 9

#include <stdio>
int main() {
  printf("VERSION = %02d\n", VERSION);
  printf("%s", "@(#)VERSION: " STRING_VERSION "\n");
  return 0;
}

Yes, you do need the double indirection in the macro call. Without it, you'd get "VERSION" instead of "9".

You can read more about this in the gcc manual (although it is fully standard C/C++).

rici
  • 234,347
  • 28
  • 237
  • 341