您的位置:首页 > 运维架构 > Linux

linux的ubuntu上如何编译C和C++代码写的动态库,以及调用执行

2011-05-17 23:23 1111 查看
// 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 <iostream>
using namespace std;

int TestCPP(void)
{
cout<<"from file "<<__FILE__<<", line: "<<__LINE__<<endl;
return 0;
}


3. main文件,生成可执行文件

main.cpp

// jernymy 20110517 main cpp module(.cpp) for exec
// main.cpp

#include "testc.h"   // testc module
#include "testcpp.h" // testcpp module

int main(void)
{
TestC();   // call .c   method
TestCPP(); // call .cpp method
}


二、通过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-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
linux-gate.so.1 =>  (0xb8035000)
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$


接下来,您也可以编写这样的例子了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: