繁体   English   中英

从共享库调用函数

[英]Calling functions from a shared library

我试图从共享库的函数中调用“核心”函数,但得到:

./a.out: symbol lookup error: ./libtest.so: undefined symbol: testf

我使用的代码非常基本,因为我只是开始编写共享库,并且仅用于测试目的:main.h

extern void testf();

main.c

#include <stdio.h>
#include <dlfcn.h>

extern void testf()
{
    printf("bla bla\n");
}

int main () {

void *handle = NULL;
void (*testlib)(void) = NULL;

handle = dlopen("./libtest.so" ,RTLD_LAZY);
testlib = dlsym(handle, "testfunc");

if ( testlib == NULL ) 
{
    printf("Error: %s \n", dlerror());
}
else 
{
    testlib();
}
}

libtest.c

#include <stdio.h>
#include "main.h"

void testfunc() {

printf("Test plugin\n");
testf();
}

和我用以下命令编译的命令:

gcc -fPIC -g -c -Wall libtest.c
gcc -shared -Wl,-soname,libtest.so.1 -o libtest.so libtest.o -lc
gcc main.c -ldl

有可能实现这一目标吗? 试图找到答案,但是真的不知道如何正确地形成问题,因此我可以更好地进行搜索。

谢谢!

在这里,您尝试从库中调用可执行文件的功能。 我认为您实际上需要与此相反。

抱歉,设法找到答案:我正在使用错误的参数编译主程序,应使用:

gcc main.c -ldl -rdynamic

暂无
暂无

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

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