文章目录
1.动态链接库项目
1.1linux eclipse创建动态链接库项目
创建工程new->project->c++ project选择Shared Library->Empty Project.输入工程名"Your Project" ,点击finish,完成工程的创建。
1.2 Hello Project项目源码:
/* libHello.so * HelloWorld.h * * Created on: 2013年12月26日 * Author: Ron Tang */ #ifndef HELLOWORLD_H_ #define HELLOWORLD_H_ extern "C" void hello(); #endif /* HELLOWORLD_H_ */
/* * libHello.so * HelloWorld.cpp * * Created on: 2013年12月26日 * Author: Ron Tang */ #include <iostream> using std::cout; using std::endl; extern "C" void hello(){ cout<<"Hello World"<<endl; }
1.3 编译动态链接库时可能遇到的错误
Building target: libHello.so
Invoking: GCC C++ Linker
g++ -shared -o "libHello.so" ./src/HelloWorld.o
/usr/bin/ld: ./src/HelloWorld.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
./src/HelloWorld.o: could not read symbols: Bad value
collect2: ld 返回 1
make: *** [libHello.so] 错误 1
1.4 解决办法
project ->properties->setting ->tool setting->complier如下图所示 添加-fPIC
2.可执行项目
2.1Linux eclipse创建可执行项目
.......
2.2 hao123项目代码(非广告,名字乱起的,请勿纠结)
/* * LoadSo.cpp * * Created on: 2013年12月26日 * Author: Ron Tang */ #include <iostream> #include <dlfcn.h> int main() { using std::cout; using std::cerr; cout << "C++ dlopen demo\n\n"; // open the library cout << "Opening hello.so...\n"; void* handle = dlopen("YourPath/libHello.so", RTLD_LAZY); if (!handle) { cerr << "Cannot open library: " << dlerror() << '\n'; return 1; } // load the symbol cout << "Loading symbol hello...\n"; typedef void (*hello_t)(); hello_t hello = (hello_t) dlsym(handle, "hello"); if (!hello) { cerr << "Cannot load symbol 'hello': " << dlerror() << '\n'; dlclose(handle); return 1; } // use it to do the calculation cout << "Calling hello...\n"; hello(); // close the library cout << "Closing library...\n"; dlclose(handle); }
2.3 编译加载动态库项目时可能遇到的错误
undefined reference to `dlopen'
undefined reference to `dlsym'
undefined reference to `dlsym'
2.4 解决办法
project->properties->setting ->tool setting ->linker 如下图所示 添加dl