从您的 main 公开一个可以{ function_name, function_pointer}
在地图中注册新元组的函数(如其他答案所建议的那样)。
通常:
// main.h
typedef void (*my_function)(void *);
int register_function(const std::string &name, my_function function);
// main.c
int register_function(const std::string &name, my_function function)
{
static std::map<std::string, my_function> s_functions;
s_functions[name] = function;
return 0;
}
int main()
{
for( std::map<std::string, my_function>::const_iterator i=s_functions.begin();
i != s_functions.end();
++i)
{
if( i->second )
{
// excecute each function that was registered
(my_function)(i->second)(NULL);
}
}
// another possibility: execute only the one you know the name of:
std::string function_name = "hello";
std::map<std::string, my_function>::const_iterator found = s_functions.find(function_name);
if( found != s_functions.end() )
{
// found the function we have to run, do it
(my_function)(found->second)(NULL);
}
}
现在,在实现要运行的功能的每个 auther 源文件中,执行以下操作:
// hello.c
#include "main.h"
void my_hello_function(void *)
{
// your code
}
static int s_hello = register_function("hello", &my_hello);
这意味着每次您使用这种语句添加新的源文件时,它都会自动添加到您可以执行的函数列表中。