How do I concatenate two macros with a dot between them without inserting spaces?

久未见 提交于 2019-12-13 12:38:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14396139/how-do-i-concatenate-two-macros-with-a-dot-between-them-without-inserting-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!