- 查看符号表,注意C库和C++库输出区别,能够看到C++的版本
# Ubuntu 调用
$ nm -D libfoo.so
# C版本,Mac 调用
$ nm -g -C --defined-only libfoo.dylib
extern "C"
#include <stdio.h>
int foo(int a, int b)
{
return a + b;
}
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
typedef int (*FUNC_FOO)(int, int);
int main()
{
printf("dlsym func demo\n");
void *handle = dlopen("./libfoo.dylib", RTLD_LAZY);
if (handle == NULL)
{
printf("dlopen error (%s)\n", dlerror());
exit(-1);
}
FUNC_FOO foo = dlsym(handle, "foo");
if (foo == NULL)
{
printf("dldym error (%s)\n", dlerror());
exit(-1);
}
int ret = foo(1, 2);
printf("ret=%d\n", ret);
return 0;
}
cmake_minimum_required(VERSION 3.0.0)
project(dlsym VERSION 0.1.0)
add_library(foo SHARED foo.c)
add_executable(dlsym dlsym.c)