Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C preprocessor: stringification does not work

I want to declare a static const array, which contains string with version info.

I already have two macros with version numbers and I want to generate an initial const string based on it.

I am trying to use the approach described here, but it does not work as it is expected with available compiler tools.

My code is next:

#define API_VERSION_MAJOR 4
#define API_VERSION_MINOR 47

#define _STR(x) #x
#define STR(x) _STR(x)

static const char OSAPIVersion[] =
    STR(API_VERSION_MAJOR) "." STR(API_VERSION_MINOR) ;

When I print the array, its value is "API_VERSION_MAJOR.API_VERSION_MINOR" instead of "4.47".

I use a customized GCC 4.4.1 ARM cross-compiler.

When I do the same on my PC with Cygwin GCC 4.5.3, it works.

Thank you in advance for your help.

UPDATE:

It turned out that API_VERSION_MAJOR and API_VERSION_MINOR macros were unvisible in a source file. I just missed the include. So simple. Too simple to be obvious.

Note that there is not any warning output in this case.

like image 864
yurko Avatar asked Apr 21 '16 09:04

yurko


1 Answers

Then your customized GCC 4.4.1 ARM cross-compiler is buggy.

If you compiled it yourself, sometimes it helps to disable some overly aggressive optimization options that might have not all their kinks ironed out.

Thinking outside the box, you might adjust the source code to avoid the problem:

#define API_VERSION_MAJOR "4"
#define API_VERSION_MINOR "47"
static const char OSAPIVersion[] = API_VERSION_MAJOR "." API_VERSION_MINOR;

or maybe construct the string at run-time:

#define API_VERSION_MAJOR 4
#define API_VERSION_MINOR 47
static char OSAPIVersion[8];
int main(void) {
  snprintf (OSAPIVersion, sizeof OSAPIVersion, "%d.%d", API_VERSION_MAJOR, API_VERSION_MINOR);
}
like image 63
Jens Avatar answered Sep 28 '22 07:09

Jens