C语言 用于在 C 中连接两个字符串的宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2191316/
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-09-02 04:22:37  来源:igfitidea点击:

Macro for concatenating two strings in C

cstringc-preprocessor

提问by Idan

I'm trying to define a macro which is suppose to take 2 string values and return them concatenated with a one space between them. It seems I can use any character I want besides space, for example:

我正在尝试定义一个宏,它假设采用 2 个字符串值并返回它们,它们之间用一个空格连接。除了空格,我似乎可以使用任何我想要的字符,例如:

#define conc(str1,str2) #str1 ## #str2 
#define space_conc(str1,str2) conc(str1,-) ## #str2

space_conc(idan,oop);

space_concwould return "idan-oop"

space_conc会返回“idan-oop”

I want something to return "idan oop", suggestions?

我想要一些东西返回“idan oop”,建议?

回答by falstro

Try this

尝试这个

#define space_conc(str1,str2) #str1 " " #str2

The '##' is used to concatenate symbols, not strings. Strings can simply be juxtaposed in C, and the compiler will concatenate them, which is what this macro does. First turns str1 and str2 into strings (let's say "hello" and "world" if you use it like this space_conc(hello, world)) and places them next to each other with the simple, single-space, string inbetween. That is, the resulting expansion would be interpreted by the compiler like this

'##' 用于连接符号,而不是字符串。字符串可以简单地在 C 中并列,编译器将它们连接起来,这就是这个宏的作用。首先将 str1 和 str2 转换为字符串(如果您像这样使用它,我们可以说“hello”和“world” space_conc(hello, world))并将它们彼此相邻放置,中间是简单的单空格字符串。也就是说,由此产​​生的扩展将被编译器这样解释

"hello" " " "world"

which it'll concatenate to

它将连接到

"hello world"

HTH

HTH

Edit
For completeness, the '##' operator in macro expansion is used like this, let's say you have

编辑
为了完整起见,宏扩展中的“##”运算符是这样使用的,假设您有

#define dumb_macro(a,b) a ## b

will result in the following if called as dumb_macro(hello, world)

如果调用为,将导致以下结果 dumb_macro(hello, world)

helloworld

which is not a string, but a symbol and you'll probably end up with an undefined symbol error saying 'helloworld' doesn't exist unless you define it first. This would be legal:

这不是一个字符串,而是一个符号,你可能会得到一个未定义的符号错误,说“helloworld”不存在,除非你先定义它。这将是合法的:

int helloworld;
dumb_macro(hello, world) = 3;
printf ("helloworld = %d\n", helloworld); // <-- would print 'helloworld = 3'

回答by Thomas Bonini

#define space_conc(str1, str2) #str1 " " #str2
printf("%s", space_conc(hello, you)); // Will print "hello you"

回答by Michael Haephrati

The right was to do it is to place the 2 strings one next to the other. '##' won't work. Just:

正确的做法是将 2 根弦并排放置。“##”不起作用。只是:

#define concatenatedstring string1 string2