Can I automatically compile a list of functions using C Macro

I want the automatic collection of a function list to start with FUN_BEGIN () and the macro FUN_END () 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() 

The code will expand as shown 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(); } 

Can I free this?

0
source share
3 answers

This uses an approach that uses constructors to add to the list, allowing you to use precise syntax.

 #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(); \ } \ } 

Note that constructors do not necessarily call in the order in which they are declared, so you may need to use __LINE__ in a macro to sort the list by line number of the definition.

+3
source

One option might be to put your definitions in a separate file

funcs.def :

 FUN_DEFINE(f1) { printf("f1\n"); } FUN_DEFINE(f2) { printf("f2\n"); } FUN_DEFINE(f3) { printf("f3\n"); } 

then in a different source file do something like

 #define FUN_DEFINE(name) static bool name(void) #include "funcs.def" #undef FUN_DEFINE void global_fun(void) { #define FUN_DEFINE(name) name(); #include "funcs.def" #undef FUN_DEFINE } 

There is a name for this approach, but I can’t remember it.

0
source

Alternative solution:

 typedef bool (*func_t) (void); // ...place function prototypes anywhere in scope funct_t test_functions [] = { &f1, &f2, &f3 }; #define TEST_FUNCTIONS_N (sizeof(test_functions) / sizeof(funct_t)) void global_fun(void) { for(size_t i=0; i<TEST_FUNCTIONS_N; i++) { test_functions[i](); } } 
0
source

Source: https://habr.com/ru/post/956241/


All Articles