Concatenating strings in macros - C++

33,206

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)
Share:
33,206
Switch
Author by

Switch

Updated on July 22, 2020

Comments

  • Switch
    Switch almost 4 years

    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.