modelu_c.h:
#ifndef _MODULE_C_H_ #define _MODULE_C_H_ #ifdef __cplusplus extern C { #endif extern int add_nums(int m, int n); #ifdef __cplusplus }; #endif #endif //end of _MODULE_C_H_module_c.c
#include "module_c.h" int add_nums(int m, int n) { return m+n; }
test.c
#include <stdio.h> int main() { int ret = 0; ret=add_nums(3, 7); printf("result is %d\n", ret); return 0; }
gcc module_c.c -fPIC -shared -o libmodulec.so
查看文件格式:
yanbo@ubuntu:~/projects/swig_prj$ file libmodulec.so libmodulec.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, BuildID[sha1]=0xa6de85a6dc105358dd2046a770862f6ac7001fa7, not stripped
gcc test.c -L. -lmodulec -o test
yanbo@ubuntu$ ldd test linux-gate.so.1 => (0xb772e000) libmodulec.so => not found libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb7556000) /lib/ld-linux.so.2 (0xb772f000)通过搜索,原因为-L.所指定的当前目录不在LD_LIBRARY_PATH全局变量记录之内,所以无法找到相应动态库。以下为一篇解决该问题的博客: ldd xxx.so not found解决方案,在此感谢作者。以方法一为例:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/yanbo/projects/swig_prj/重新ldd:
yanbo@ubuntu$ ldd test linux-gate.so.1 => (0xb772e000) libmodulec.so => (0xb773a000) libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb7556000) /lib/ld-linux.so.2 (0xb772f000)执行调用:
yanbo@ubuntu:~/projects/swig_prj$ ./test result is 10调用成功。