Concatenate int to string using C Preprocessor

CC PreprocessorStringification

C Problem Overview


I'm trying to figure out how I can concatenate a #define'd int to a #define'd string using the C Preprocessor. My compiler is GCC 4.1 on CentOS 5. The solution should also work for MinGW.

I'd like to append a version number onto a string, but the only way I can get it to work is to make a copy of the version number defines as strings.

The closest thing I could find was a method of quoting macro arguments, but it doesn't work for #defines

This is does not work.

#define MAJOR_VER 2
#define MINOR_VER 6
#define MY_FILE "/home/user/.myapp" #MAJOR_VER #MINOR_VER

It doesn't work without the #s either because the values are numbers and it would expand to "/home/user/.myapp" 2 6, which isn't valid C.

This does work, but I don't like having copies of the version defines because I do need them as numbers as well.

#define MAJOR_VER 2
#define MINOR_VER 6
#define MAJOR_VER_STR "2"
#define MINOR_VER_STR "6"
#define MY_FILE "/home/user/.myapp" MAJOR_VER_STRING MINOR_VER_STRING

C Solutions


Solution 1 - C

Classical C preprocessor question....

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#define MAJOR_VER 2
#define MINOR_VER 6
#define MY_FILE "/home/user/.myapp" STR(MAJOR_VER) STR(MINOR_VER)

The extra level of indirection will allow the preprocessor to expand the macros before they are converted to strings.

Solution 2 - C

A working way is to write MY_FILE as a parametric macro:

#define MY_FILE(x,y) "/home..." #x #y

EDIT: As noted by "Lindydancer", this solution doesn't expand macros in arguments. A more general solution is:

#define MY_FILE_(x,y) "/home..." #x #y
#define MY_FILE(x,y) MY_FILE_(x,y)

Solution 3 - C

You can do that with BOOST_PP_STRINGIZE:

#define MAJOR_VER 2
#define MINOR_VER 6
#define MY_FILE "/home/user/.myapp" BOOST_PP_STRINGIZE(MAJOR_VER) BOOST_PP_STRINGIZE(MINOR_VER)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjonescbView Question on Stackoverflow
Solution 1 - CLindydancerView Answer on Stackoverflow
Solution 2 - CGiuseppe GuerriniView Answer on Stackoverflow
Solution 3 - CMaxim EgorushkinView Answer on Stackoverflow