在 Linux 下用 C++ 生成动态库(.so 文件),一般步骤如下:
例如有两个文件:
hello.h#ifndef HELLO_H
#define HELLO_H
void say_hello();
#endif
hello.cpp#include <iostream>
#include "hello.h"
void say_hello() {
std::cout << "Hello from dynamic library!" << std::endl;
}
使用 g++ 的 -fPIC 和 -shared 参数:
g++ -fPIC -shared hello.cpp -o libhello.so
说明:
-fPIC:生成位置无关代码(必须)-shared:生成共享库libxxx.so:Linux 动态库命名规范main.cpp#include "hello.h"
int main() {
say_hello();
return 0;
}
g++ main.cpp -L. -lhello -o main
参数说明:
-L.:在当前目录找库-lhello:链接 libhello.so./main
如果报错:
error while loading shared libraries: libhello.so
需要指定库路径:
export LD_LIBRARY_PATH=.
./main
或把 .so 放到 /usr/lib 等系统目录。
nm -D libhello.so
ldd main
如果库要被 C 或其他语言调用,建议加 extern "C":
extern "C" {
void say_hello();
}
libhello.so: hello.cpp
g++ -fPIC -shared hello.cpp -o libhello.so
main: main.cpp libhello.so
g++ main.cpp -L. -lhello -o main
clean:
rm -f libhello.so main
如果你需要:
可以继续问我。