Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings in macros - C++

What's the easiest way to concatenate strings defined in macros. i.e. The pseudo code I'm looking for would be like:

#define ROOT_PATH "/home/david/"
#define INPUT_FILE_A ROOT_PATH+"data/inputA.bin"
#define INPUT_FILE_B ROOT_PATH+"data/inputB.bin"
...
#define INPUT_FILE_Z ROOT_PATH+"data/inputZ.bin"

The only way I know of is to use strcat in the code, or using the string class and then the c_str method, but it can get messy when I have lots of input files. I'd like to just use INPUT_FILE_A, etc. directly and not have lots of local variables. Is there a good way to do this?

Thanks.

like image 273
Switch Avatar asked Nov 15 '09 22:11

Switch


People also ask

How do you concatenate strings in C?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

How do you concatenate 2 strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

What is concatenation of macro parameters?

Concatenation means joining two strings into one. In the context of macro expansion, concatenation refers to joining two lexical units into one longer one. Specifically, an actual argument to the macro can be concatenated with another actual argument or with fixed text to produce a longer name.


1 Answers

The compiler will automatically concatenate adjacent strings:

#define ROOT_PATH "/home/david/"
#define INPUT_FILE_A ROOT_PATH "data/inputA.bin"

Or more generic:

#define INPUT_FILE_DETAIL(root,x) root #x
#define INPUT_FILE(x) INPUT_FILE_DETAIL(ROOT_PATH "data/", x)
like image 141
GManNickG Avatar answered Oct 07 '22 15:10

GManNickG