Can I use C-preprocssor to convert an integer to a string?

There must be a way to do this ...

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

#define VERSION 9

and several files use a specific VERSION as an integer. It's fine.

Without changing the way VERSION is defined, I need to create an initialized "what" string that contains this 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 VERSION value, essentially giving this ...

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

Any ideas? Is it possible?

+5
source share
2 answers

"stringify" (#), , :

#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;
}

, . "VERSION" "9".

gcc ( C/++).

0

, . .

K & R :

 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.

- . #define , char *version=

+5

All Articles