我可以通过C宏自动收集功能列表 [英] Can I auto collect a list of function by C Macro
本文介绍了我可以通过C宏自动收集功能列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想自动收集函数列表,开始FUN_BEGIN()& FUN_BEGIN()
FUN_DEFINE(f1)FUN_END()宏,如果我将它写为:
I want to auto collect a list of functions begin FUN_BEGIN() & FUN_END() macro, if I write it as:
FUN_BEGIN()
FUN_DEFINE(f1) {
printf("f1\n"); }
FUN_DEFINE(f2) {
printf("f2\n"); }
FUN_DEFINE(f3) {
printf("f3\n"); }
FUN_END()
代码如下展开: p>
The code will expand as below:
static bool f1(void)
{
printf("f1\n");
}
static bool f2(void)
{
printf("f2\n");
}
static bool f3(void)
{
printf("f3\n");
}
void global_fun(void)
{
f1();
f2();
f3();
}
我可以将其释放吗?
推荐答案
这是一种使用构造函数添加到列表中的方法,它允许使用确切的语法。
Here's an approach that uses constructors to add to a list, permitting the exact syntax you used.
#define FUN_BEGIN() struct __fun_list { \
struct __fun_list *next; \
bool (*f)(void); \
} *head = NULL; \
static void globals_list_add(bool (*f)(void)) { \
/* add f to the linked list... */ \
}
#define FUN_DEFINE(f) static bool f(void);\
static void __attribute__((constructor)) __construct_##f(void) {\
globals_list_add(f); \
} \
static bool f(void)
#define FUN_END() void global_fun(void) { \
struct __fun_list *cur; \
for(cur = head; cur; cur = cur->next) { \
cur->f(); \
} \
}
注意构造函数不一定叫按照它们被声明的顺序,所以你可能需要在宏中使用 __ LINE __
来按定义的行号对列表进行排序。
Note the constructors are not necessarily called in the order they are declared, so you may need to use __LINE__
in the macro to sort the list by the line number of the definition.
这篇关于我可以通过C宏自动收集功能列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文