Question

The version number in my code is defined in a few formats which requires me to change more than one definition when I go up in the version:

#define VERSION_N       0x0203
#define SERIALNUMBER_STR    L"2.0.3"

and so on.

I'd like to centralize it to one single definition. Something like:

#define VER_X_  0
#define VER_H_  2
#define VER_M_  0
#define VER_L_  3

#define VERSION_N   VER_L_ + 0x10*VER_M_ + 0x100*VER_H_ + 0x1000*VER_X_
#define SERIALNUMBER_STR    ??????????????
Was it helpful?

Solution 2

Here's the tested solution:

#define VER_X_  0
#define VER_H_  2
#define VER_M_  0
#define VER_L_  3



#define VERSION_N (VER_L_ + 0x10*VER_M_ + 0x100*VER_H_ + 0x1000*VER_X_)

// Device Strings
//
#define STRINGIFY_1(x)   L#x
#define STRINGIFY(x)     STRINGIFY_1(x)
#define PASTE(x, y) x##y
#define MAKEWIDE(x) PASTE(L,x)

#define SERIALNUMBER_STR MAKEWIDE(STRINGIFY(VER_H_)) L"." \
                         MAKEWIDE(STRINGIFY(VER_M_)) L"." \
                         MAKEWIDE(STRINGIFY(VER_L_))

Thanks to ouah

EDIT:

  1. Added parentheses according to pat.
  2. Ouah's remark was taken seriously. Solution adapted to suit MS: Added two PASTE & MAKEWIDE

OTHER TIPS

Use a stringify macro:

#define STRINGIFY_1(x...)   #x
#define STRINGIFY(x...)     STRINGIFY_1(x)

#define VER_X_  0
#define VER_H_  2
#define VER_M_  0
#define VER_L_  3

#define SERIALNUMBER_STR  STRINGIFY(VER_H_) L"." STRINGIFY(VER_M_)  \
                          L"." STRINGIFY(VER_L_)

EDIT1: I added the L in L"." to have wide strings. I don't put a L#x as it got expanded with a space and something in the form L "string" is not a string literal in C. Nevertheless concatenating a string literal and a wide string literal result in a wide string literal.

EDIT2: As put in the comments, the example above work with the last revisions of C (c99 and c11) but not with c89 (i.e., not with MSVC). First reason is variadic macros are not supported in c89. The second reason is in c99 you can concatenate a character string literal and a wide string literal but in c89 this is undefined behavior. Below is a standard solution that also work in c89:

#define CAT(x, y)  x##y
#define WIDE(x)    CAT(L,x)

#define STRINGIFY_1(x)   #x
#define STRINGIFY(x)     STRINGIFY_1(x)

#define VER_X_  0
#define VER_H_  2
#define VER_M_  0
#define VER_L_  3

#define SERIALNUMBER_STR  WIDE(STRINGIFY(VER_H_)) L"." WIDE(STRINGIFY(VER_M_))  \
                          L"." WIDE(STRINGIFY(VER_L_))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top