I always forget how to stringify and to concatenate values with cpp. These functions have particularity to need to called two times because of weird behavior of cpp with prescan feature (prescan is not applied if macro contains # or ##).

Change a value in string:

 #define __STRINGIFY(X)      #X
 #define STRINGIFY(X)        __STRINGIFY(X)

Concatenate 2, 3 or 4 values:

 #define __CONCAT2(X, Y)       X ## Y
 #define CONCAT2(X, Y)        __CONCAT2(X, Y)
 #define __CONCAT3(X, Y, Z)    X ## Y ## Z
 #define CONCAT3(X, Y, Z)     __CONCAT3(X, Y, Z) 
 #define __CONCAT4(W, X, Y, Z) W ## X ## Y ## Z
 #define CONCAT4(W, X, Y, Z)  __CONCAT4(W, X, Y, Z)

Some tests:

  • Input
 #define _VAR1_ var1
 #define _VAR2_ var2
 #define _VAR3_ var3
 #define _VAR4_ var4
 #define RESULT CONCAT3(text, _VAR1_, _VAR2_)
 
 RESULT
 STRINGIFY(_VAR1_)
 STRINGIFY(const)
 CONCAT2(_VAR1_, _VAR2_)
 CONCAT3(_VAR1_, _VAR2_, _VAR3_)
 CONCAT4(_VAR1_, _VAR2_, _VAR3_, _VAR4_)
 CONCAT4(_VAR1_, const, _VAR3_, const)
  • Output:
 textvar1var2
 "var1"
 "const"
 var1var2
 var1var2var3
 var1var2var3var4
 var1constvar3const

Source file there