linux 的 ubuntu 上如何编译 C 和 C++代码写的动态库,以及调用执行
// 20110517 jernymy
// 今天是电信日,下班时看到手机报上的中国电信下调资费新闻,很是高兴。
环境 VMware+Ubuntu9.04
一、作为测试用,当前目录有这样几个文件
1. testc 的模块的文件,生成 so
testc.h
// jernymy 20110517 test c module(.h) for so linker
// testc.h
#ifndef _TESTC_H_
#define _TESTC_H_
// here used extern "C"
#ifdef __cplusplus
extern "C" {
#endif
int TestC(void);
#ifdef __cplusplus
}
#endif
#endif
-----------------------------------------------------------------------------------------------------
testc.c
// jernymy 20110517 test c module(.c) for so linker
// testc.c
#include "stdio.h"
int TestC(void)
{
printf("from file %s, line: %d\n", __FILE__, __LINE__);
return 0;
}
2. testcpp 的模块的文件,生成 so
testcpp.h
// jernymy 20110517 test cpp module(.h) for so linker
// testcpp.h
#ifndef _TESTCPP_H_
#define _TESTCPP_H_
int TestCPP(void);
#endif
---------------------------------------------------------------------------------------------------
testcpp.cpp
// jernymy 20110517 test cpp module(.cpp) for so linker
// testcpp.cpp
#include
using namespace std;
int TestCPP(void)
{
cout<<"from file "<<__FILE__<<", line: "<<__LINE__<二、通过 ubuntu 的 gcc 编译 testc.c, testcpp.cpp 生成 libtest.so。
main.cpp 生成 mtest
jernymy@jernymy-desktop$ gcc -o libtest.so testc.c testcpp.cpp -shared -lstdc++
jernymy@jernymy-desktop$
jernymy@jernymy-desktop$ gcc -o mtest -I ./ main.cpp -L . -ltest -lstdc++
三、执行 mtest,发现无法找到 libtest.so。
这时通过 ldd 查看 mtest 依附的 lib 的情况,发现 libtest.so => not found,
需要将当前(生成的 libtest.so)目录加入到 lib 的 so 搜索路径
jernymy@jernymy-desktop$
jernymy@jernymy-deskto$ ./mtest
./mtest: error while loading shared libraries: libtest.so: cannot open shared object file: No such
file or directory
jernymy@jernymy-deskto$ ldd ./mtest
(0xb8035000)
linux-gate.so.1 =>
libtest.so => not found
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7f37000)
libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb7dd3000)
libm.so.6 => /lib/tls/i686/cmov/libm.so.6 (0xb7dad000)
/lib/ld-linux.so.2 (0xb8036000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb7d9e000)
jernymy@jernymy-desktop$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:./
jernymy@jernymy-desktop$ ./mtest
from file testc.c, line: 5
from file testcpp.cpp, line: 7
jernymy@jernymy-desktop$
接下来,您也可以编写这样的例子了。
本 文 来 自 CSDN 博 客 , 转 载 请 标 明 出 处 :
http://blog.csdn.net/jernymy/archive/2011/05/17/6428210.aspx