从共享库调用函数 [英] Calling functions from a shared library
本文介绍了从共享库调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从共享库的函数中调用核心"函数,但我得到:
I'm trying to call a "core" function from a shared library's function but I get:
./a.out: symbol lookup error: ./libtest.so: undefined symbol: testf
我使用的代码非常基础,因为我刚刚开始编写共享库,并且仅用于测试目的:main.h
The code I'm using is very basic because I'm just getting into writing shared libraries and it's just for testing purposes: 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();
}
以及我用来编译它的命令:
And the commands I compile it with:
gcc -fPIC -g -c -Wall libtest.c
gcc -shared -Wl,-soname,libtest.so.1 -o libtest.so libtest.o -lc
gcc main.c -ldl
有可能实现吗?试图找到答案,但真的不知道如何正确地形成问题,以便我可以更好地搜索它.
Is it possible to achieve this? Tried to find the answer, but don't really know how to form the question right so I can search better for it.
谢谢!
推荐答案
抱歉,找到了答案:我在编译主程序时使用了错误的参数,应该使用:
Sorry, managed to find the answer: I was compiling the main program with wrong parameters, should use:
gcc main.c -ldl -rdynamic
这篇关于从共享库调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文