如何从 C 中的宏函数返回字符串?
我想根据作为参数传递给宏函数的值创建一个字符串。 类似的东西:
#define ABC(x,y) return "anystr_x_y.tar.bz2"
main()
{
a = ABC(2,3);
}
所以最后,它应该返回“anystr_2_3.tar.bz2”
我想知道如何使用作为参数传递给 MACRO fnc 的值创建该字符串。
任何帮助! 谢谢 !
I want to create a string based on the value passed as argument to the MACRO FUNCTION.
Something Like:
#define ABC(x,y) return "anystr_x_y.tar.bz2"
main()
{
a = ABC(2,3);
}
So Finally, It should return "anystr_2_3.tar.bz2"
I was wondering how to create that string with the value passed as argument to MACRO fnc.
Any help !
thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用“字符串化运算符”定义宏:
Define your macro like this, using the "stringize operator":
宏不返回内容,因为它们不是函数。它们只是令牌替换功能。你真正想要的是一个虽然,在你的位置我会用一个函数来代替。但是,解决方案可能如下所示:
这利用了字符串文字折叠在一起的事实,因此
"Hello " "World!"
被解释为"Hello World!"
。Macros don't return stuff, since they are not functions. They are merely token replacement functionality. What you actually want is a though one, and in your place I would do it with a function instead. However, a solution could look like:
This takes leverage from the fact that string literals are collapsed togheter, so
"Hello " "World!"
is interpreted as"Hello World!"
.C 中(C++ 中也不存在宏函数)这样的东西。在编译代码之前,宏由预处理器处理。上面的示例代码将由编译器处理为:
为了实现您想要执行的操作,您需要告诉预处理器连接 x、y 和字符串的常量部分。您可以使用 ## 运算符来执行此操作,例如:
这将导致以下代码被传递给编译器:
There is no such thing as a macro function in C (nor C++). Macros are processed by the preprocessor, before the code is compiled. Your example code above will be processed by the compiler to this:
To achieve what you are trying to do, you need to tell the preprocessor to concattenate x, y and the constant parts of your string. You do that using the ## operator, e.g.:
That will result in the following code being passed to the compiler: