- 论坛徽章:
- 0
|
程序1 s.cpp
- int soTest(int a,int b)
- {
- return a+b;
- }
复制代码
编译:
g++ -c s.cpp
g++ -shared -o s.so s.o
程序2 t.cpp
- #include <stdio.h>;
- #include <stdlib.h>;
- #include <dlfcn.h>;
- int main(int argc, char **argv)
- {
- void *handle;
- int (*soTest)(int,int);
- char *error;
- handle = dlopen ("./s.so", RTLD_LAZY);
- if (!handle)
- {
- fprintf (stderr, "%s\n", dlerror());
- exit(1);
- }
- (void *)soTest = (int (*)(int,int))dlsym(handle, "soTest");
- if ((error = dlerror()) != NULL)
- {
- fprintf (stderr, "%s\n", error);
- exit(1);
- }
- printf ("%d\n", (*soTest)(2,3));
- dlclose(handle);
- return 0;
- }
复制代码
编译:
g++ -c t.cpp
g++ -o t t.o -ldl
但运行时提示 undefined symbol: soTest
一样的程序使用 gcc 编译可以运行,但 g++ 却不行。
不知 unix 下 c++ 的程序该如何使用动态库呢?
我希望把一个程序设计成模块化,允许使用动态库动态载入扩充功能,这样只需按一定的规范做成动态库即可无需重新编译和重新启动主程序即可实现扩展与停止模块。
因为系统使用 c++ 开发,所以必须使用 g++ 编译动态库,遇到点麻烦,有兴趣的朋友请指点一下。 |
|