Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate int to string using C Preprocessor

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 
like image 623
jonescb Avatar asked Mar 28 '11 13:03

jonescb


People also ask

Can you concatenate an int to a string in C?

Use asprintf , strcat and strcpy Functions to Concatenate String and Int in C. The first step to concatenating int variable and the character string is to convert an integer to string. We utilize asprintf function to store the passed integer as a character string.

What is ## preprocessor operator in C?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.

Can I concatenate strings in C?

As you know, the best way to concatenate two strings in C programming is by using the strcat() function.

What is macro concatenation in C?

Macro Concatenation with the ## OperatorThe ## (double number sign) operator concatenates two tokens in a macro invocation (text and/or arguments) given in a macro definition. If a macro XY was defined using the following directive: #define XY(x,y) x##y.


1 Answers

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.

like image 78
Lindydancer Avatar answered Oct 05 '22 01:10

Lindydancer