23,120
社区成员
发帖
与我相关
我的任务
分享
一、作为测试用,当前目录有这样几个文件
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-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
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$
接下来,您也可以编写这样的例子了。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jernymy/archive/2011/05/17/6428210.aspx