下面给出在Linux平台下将C++源代码编译为动态库的示例代码。
首先,编写一个简单的C++源代码文件example.cpp,如下所示:
#include
void say_hello() { std::cout << "Hello from dynamic library!" << std::endl; }
接下来,使用g++命令将源代码编译为动态库,命令如下所示:
g++ -shared -o libexample.so example.cpp
其中,-shared选项表示生成动态库,-o选项指定输出文件名为“libexample.so”。
接着,我们在另一个C++源代码文件main.cpp中调用这个动态库中的函数,代码如下所示:
#include
int main() { // 加载动态库 void* handle = dlopen("./libexample.so", RTLD_LAZY); if (!handle) { std::cerr << dlerror() << std::endl; return 1; }
// 获取函数指针并调用
typedef void (*HelloFunc)();
HelloFunc hello = (HelloFunc) dlsym(handle, "say_hello");
if (!hello) {
std::cerr << dlerror() << std::endl;
return 1;
}
hello();
// 卸载动态库
dlclose(handle);
return 0;
}
在该代码中,我们使用了dlfcn.h头文件中的dlopen()、dlsym()和dlclose()函数来加载动态库、获取函数指针并调用和卸载动态库。运行该代码,即可在终端输出“Hello from dynamic library!”的消息。