简体   繁体   English

使用宏命名C中的函数

[英]Using macros to name functions in C

The other day I was trying to use a macro to define a function like so (simplified, obviously): 前几天,我试图使用宏来定义这样的函数(显然是简化的):

#define DEF_ADD(name) \
    int add_name(int x, int y) { \
        return x + y; \
    } \

Now, I expected the snippet DEF_ADD(hello) to define the function add_hello . 现在,我希望代码段DEF_ADD(hello)定义函数add_hello However, the macro call instead defines a function called add_name . 但是,宏调用定义了一个名为add_name的函数。 I expect that this has something to do with scanning, but I couldn't find a way to recreate the behavior I'm looking for. 我希望这与扫描有关,但我找不到重新创建所需行为的方法。 Any ideas how to do this? 任何想法如何做到这一点?

You need 你需要

#define DEF_ADD(name) \
    int add_##name(int x, int y) { \
    return x + y; \
}

Note well the ## . 注意## I've also dropped the final newline character. 我还删除了最后一个换行符。 Else the parameter name is not used and you create add_name as the function name. 否则,不使用参数name ,而是将add_name创建为函数名称。

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

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