在宏中连接字符串 - C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1739102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:04:40  来源:igfitidea点击:

Concatenating strings in macros - C++

c++cstringconcatenation

提问by Switch

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?

我知道的唯一方法是在代码中使用 strcat ,或者使用字符串类然后使用 c_str 方法,但是当我有很多输入文件时它会变得混乱。我只想直接使用 INPUT_FILE_A 等,而不是有很多局部变量。有没有好的方法可以做到这一点?

Thanks.

谢谢。

回答by GManNickG

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)

回答by Alexander Samoylov

Shell was "eating" the quotes. So, the following line had to use:

壳牌正在“吃”引号。因此,必须使用以下行:

-DROOT_PATH=\"some-string"\