生成so 库demo案例
时间: 2023-12-06 13:44:56 浏览: 27
下面是一个简单的示例,演示如何生成一个简单的 C++ 动态链接库(.so 文件)。
1. 首先,编写 C++ 代码,实现所需的函数或类。例如,以下示例代码定义了一个名为 `hello` 的函数,该函数返回一个字符串。
```cpp
#include <string>
std::string hello() {
return "Hello, world!";
}
```
2. 将代码保存到一个名为 `hello.cpp` 的文件中。
3. 在终端中,使用以下命令编译代码:
```bash
g++ -c -fPIC hello.cpp -o hello.o
```
这将创建一个名为 `hello.o` 的目标文件。
4. 接下来,使用以下命令将目标文件链接到一个动态链接库中:
```bash
g++ -shared hello.o -o libhello.so
```
这将创建一个名为 `libhello.so` 的动态链接库。
5. 现在,您可以在其他 C++ 代码中使用生成的动态链接库。例如,以下代码演示如何加载动态链接库并调用其中的函数:
```cpp
#include <iostream>
#include <dlfcn.h>
int main() {
// 加载动态链接库
void* handle = dlopen("libhello.so", RTLD_LAZY);
if (!handle) {
std::cerr << "Error loading shared library: " << dlerror() << '\n';
return 1;
}
// 获取函数指针
typedef std::string (*hello_t)();
hello_t hello_func = (hello_t) dlsym(handle, "hello");
const char* dlsym_error = dlerror();
if (dlsym_error) {
std::cerr << "Error loading symbol: " << dlsym_error << '\n';
dlclose(handle);
return 1;
}
// 调用函数
std::cout << hello_func() << '\n';
// 卸载动态链接库
dlclose(handle);
return 0;
}
```
6. 编译上述代码,链接到动态链接库:
```bash
g++ main.cpp -ldl -o main
```
这将生成一个名为 `main` 的可执行文件,运行它将输出 "Hello, world!"。