简体   繁体   English

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

[英]Macro for concatenating two strings in C

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. 我正在尝试定义一个宏,假设它采用2个字符串值并返回它们之间的一个空格连接。 It seems I can use any character I want besides space, for example: 似乎我可以使用除空间之外我想要的任何角色,例如:

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

space_conc(idan,oop);

space_conc would return "idan-oop" space_conc将返回“idan-oop”

I want something to return "idan oop", suggestions? 我想要一些东西回归“idan oop”,建议?

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. 字符串可以简单地并置在C中,编译器将连接它们,这就是这个宏的作用。 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. 首先将str1和str2转换为字符串(如果你像这个space_conc(hello, world)一样使用它,请说“你好”和“世界”)并将它们放在彼此旁边,中间是简单的单空格字符串。 That is, the resulting expansion would be interpreted by the compiler like this 也就是说,由此产​​生的扩展将由编译器解释

"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. 这不是一个字符串,而是一个符号,你可能会得到一个未定义的符号错误,说'helloworld'不存在,除非你先定义它。 This would be legal: 这是合法的:

int helloworld;
dumb_macro(hello, world) = 3;
printf ("helloworld = %d\n", helloworld); // <-- would print 'helloworld = 3'
#define space_conc(str1, str2) #str1 " " #str2
printf("%s", space_conc(hello, you)); // Will print "hello you"

The right was to do it is to place the 2 strings one next to the other. 正确的做法是将2个字符串放在另一个旁边。 '##' won't work. '##'不起作用。 Just: 只是:

#define concatenatedstring string1 string2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM