如何对包含逗号的字符串进行字符串化处理? [英] How to stringify a string which contains a comma?

查看:166
本文介绍了如何对包含逗号的字符串进行字符串化处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在编译命令中传递版本字符串:

I want to pass a version string in the compile command:

$ g++ -Wall -D VERSION="2013-12-03 02:15:21, commit cb060df" -o main main.cpp

在我的代码中,我有以下内容:

Inside my code, I have the following:

#define TOSTR_(x) #x
#define STRINGIFY(x) TOSTR_(x)
#define VERSION_STR STRINGIFY(VERSION)

这是行不通的,因为VERSION宏中包含逗号,因此看起来我正在向TOSTR()传递两个参数(显然,VERSION宏仅在传递给后才被扩展STRINGIFY()作为唯一参数).

This doesn't work, because the VERSION macro has a comma in it, so it looks like I'm passing two arguments to TOSTR() (apparently, the VERSION macro only gets expanded after it's passed to STRINGIFY() as one unique argument).

我在此处中找到的以下方法也不起作用:

The following approach I found in here also doesn't work:

#define CONCAT(...) __VA_ARGS__
#define TOSTR_(x) #x
#define STRINGIFY(x) TOSTR_(CONCAT(x))
#define VERSION_STR STRINGIFY(VERSION)

因为这似乎与

#define VERSIONSTR "CONCAT(2013-12-03 02:15:21, commit cb060df)"

也就是说,宏CONCAT()不会展开.

that is, the macro CONCAT() doesn't get expanded.

注1:我不希望在命令行中传递 C 字符串,因为版本字符串实际上是动态生成的,并且其中可能包含一些引号.这意味着仅编写g++ -D VERSION=\""$(GENERATED_STRING)"\"而不是对传递的参数进行字符串化将不起作用.

Note 1: I would rather not pass a C string in the command line, because the version string is actually dynamically generated, and it might contain some quotes. This means that just writing g++ -D VERSION=\""$(GENERATED_STRING)"\" instead of stringifying the passed argument wouldn't work.

注2:如果有人找到了一种完全没有任何预处理器宏的方法,我将非常高兴.

Note 2: I would be extremely happy if someone found a way of doing this without any preprocessor macros at all.

推荐答案

您可以编写TOSTR_宏以采用可变参数:

You can write the TOSTR_ macro to take variable arguments:

#define TOSTR_(x...) #x
#define STRINGIFY(x) TOSTR_(x)
#define VERSION_STR STRINGIFY(VERSION)

此代码已经过测试,可在Apple LLVM 5.0版上运行.

This code has been tested and works on Apple LLVM version 5.0.

这篇关于如何对包含逗号的字符串进行字符串化处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆