如何在两个宏之间插入一个点,而不插入空格? [英] How do I concatenate two macros with a dot between them without inserting spaces?
问题描述
我正在预处理InfoPlist文件以包括我的修订号。我的标头如下所示:
#import svn.h
#define APP_VERSION 1.0
#define APP_BUILD APP_VERSION.SVN_REVISION
当我从程序中检查构建版本时,它是 1.0。 123456
。但是,如果我尝试这样做:
#import svn.h
#define APP_VERSION 1.0
#定义APP_BUILD APP_VERSION ## ## SVN_REVISION
我知道
错误:粘贴格式为'APP_VERSION。',无效的预处理令牌
错误:粘贴格式为'.SVN_REVISION',无效的预处理令牌
我见过,但实际上并没有给出答案; OP实际上并不需要连接令牌。我做。如何在两个宏之间用点连接而不插入空格?
问题似乎是由< href = http://gcc.gnu.org/onlinedocs/cpp/Argument-Prescan.html#Argument-Prescan rel = noreferrer>预处理器的怪癖:串联运算符aren的参数首先不进行扩展(或者……不管怎样,规则都很复杂),所以当前预处理器不尝试连接 1.0
和。 / code>,它实际上是试图将单词
APP_VERSION
粘贴到输出令牌中。单词在C中没有点,因此这不是一个有效的标记,因此会出错。
通常可以通过几次操作来强制执行此操作。包装宏层,以便将连接操作隐藏在至少两个替换项之后,例如:
#define APP_VERSION 1.0
#定义SVN_REVISION 123456
#定义M_CONC(A,B)M_CONC_(A,B)
#定义M_CONC_(A,B)A ## B
#定义APP_BUILD M_CONC(APP_VERSION,M_CONC(。,SVN_REVISION))
APP_BUILD //扩展为单个令牌1.0.123456
您很幸运,因为C预处理程序编号
= noreferrer>可以根据需要添加任意数量的点。
I'm preprocessing my InfoPlist file to include my revision number. My header looks like this:
#import "svn.h"
#define APP_VERSION 1.0
#define APP_BUILD APP_VERSION.SVN_REVISION
When I check my build version from within the program, it's 1.0 . 123456
. But if I try this:
#import "svn.h"
#define APP_VERSION 1.0
#define APP_BUILD APP_VERSION ## . ## SVN_REVISION
I get
error: pasting formed 'APP_VERSION.', an invalid preprocessing token
error: pasting formed '.SVN_REVISION', an invalid preprocessing token
I've seen this question but it doesn't actually give an answer; the OP didn't actually need to concatenate the tokens. I do. How do I concatenate two macros with a dot between them without inserting spaces?
The problem looks like it is being caused by a quirk of the preprocessor: arguments to the concatenation operator aren't expanded first (or... whatever, the rules are complicated), so currently the preprocessor isn't trying to concatenate 1.0
and .
, it's actually trying to paste the word APP_VERSION
into the output token. Words don't have dots in them in C so this is not a single valid token, hence the error.
You can usually force the issue by going through a couple of layers of wrapper macros so that the concatenation operation is hidden behind at least two substitutions, like this:
#define APP_VERSION 1.0
#define SVN_REVISION 123456
#define M_CONC(A, B) M_CONC_(A, B)
#define M_CONC_(A, B) A##B
#define APP_BUILD M_CONC(APP_VERSION, M_CONC(.,SVN_REVISION))
APP_BUILD // Expands to the single token 1.0.123456
You're in luck in that a C Preprocessor number is allowed to have as many dots as you like, even though a C float constant may only have the one.
这篇关于如何在两个宏之间插入一个点,而不插入空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!