【问题标题】:Concatenating strings in macros - C++在宏中连接字符串 - C++
【发布时间】:2010-12-16 21:10:28
【问题描述】:

连接宏中定义的字符串的最简单方法是什么。 即我正在寻找的伪代码如下:

#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"

我知道的唯一方法是在代码中使用 strcat,或者使用 string 类,然后使用 c_str 方法,但是当我有很多输入文件时它会变得混乱。我想直接使用 INPUT_FILE_A 等,没有很多局部变量。有什么好办法吗?

谢谢。

【问题讨论】:

    标签: c++ c string concatenation


    【解决方案1】:

    编译器会自动连接相邻的字符串:

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

    或更通用的:

    #define INPUT_FILE_DETAIL(root,x) root #x
    #define INPUT_FILE(x) INPUT_FILE_DETAIL(ROOT_PATH "data/", x)
    

    【讨论】:

      【解决方案2】:

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

      -DROOT_PATH=\"some-string"\
      

      【讨论】:

        猜你喜欢
        • 2011-07-12
        • 2017-08-27
        • 1970-01-01
        • 2019-11-06
        • 2013-09-05
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        相关资源
        最近更新 更多