函数已声明,但未在共享库中定义

时间:2018-11-07 11:02:51

标签: c++ shared-libraries static-libraries

我有一些库的源代码。有一个仅在头文件中声明的函数,而未在源代码中定义。

extern "C"  {
    extern int theFunc(int);
}

在库中仅声明函数的原因是什么?

1 个答案:

答案 0 :(得分:0)

除了Mike Kinghan's answer(涵盖大多数情况)外,还有(非常不寻常的)理由要在库头文件中声明该库中未实现的函数。有时,该库需要一个plugin,并且用户应该提供这样的插件(以某种方式,可能是将插件文件名传递给其他函数)。该库将使用dynamic loading技术(例如Linux上的dlopen(3))来安装这样的插件。并且它将从插件中获取一些 specific 函数(在Linux上为dlsym(3))。然后,在库头文件中 declare 有意义,但 define 这样的插件函数却没有意义。

我确实承认这种情况不寻常且人为。

有关具体示例,请阅读有关GCC plugins的信息。您的插件应{<1>间接声明的#include "gcc-plugin.h"

/* Declaration for "plugin_init" function so that it doesn't need to be
   duplicated in every plugin.  */
extern int plugin_init (struct plugin_name_args *plugin_info,
                        struct plugin_gcc_version *version);

但是plugin_init应该由您的插件代码定义。然后,GCC将使用与{p>

dlopen

然后再使用

void*plhdl = dlopen("/home/you/yourplugin.so", RTLD_NOW);

请注意,符号 typeof(plugin_init)* funptr = dlsym(plhdl, "plugin_init"); 不会出现在GCC的代码段中。

另一个例子是Qt框架(一组库)。了解有关Qt plugins的信息。

相关问题