在 CentOS 上配置 C++ 动态库(.so),一般包括 编译生成动态库 → 配置链接 → 运行时加载 三个步骤。下面按常见流程详细说明。
假设有如下文件:
hello.cpp
hello.h
main.cpp
#ifndef HELLO_H
#define HELLO_H
void hello();
#endif
#include <iostream>
#include "hello.h"
void hello() {
std::cout << "Hello from dynamic library!" << std::endl;
}
#include "hello.h"
int main() {
hello();
return 0;
}
-fPIC)g++ -fPIC -c hello.cpp -o hello.o
-fPIC:生成位置无关代码(动态库必须)
g++ -shared -o libhello.so hello.o
✅ 生成:
libhello.so
命名规范:
libxxx.so(链接时用 -lxxx)
g++ main.cpp -o main -L. -lhello
参数说明:
| 参数 | 含义 |
|---|---|
-L. |
在当前目录查找库 |
-lhello |
链接 libhello.so |
./main
可能出现:
error while loading shared libraries: libhello.so: cannot open shared object file
原因:系统找不到动态库
LD_LIBRARY_PATH(推荐测试用)export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
./main
✅ 临时生效(终端关闭失效)
/etc/ld.so.conf.d/(推荐生产环境)sudo vim /etc/ld.so.conf.d/hello.conf
写入:
/usr/local/lib
或你的库路径:
/home/user/lib
然后执行:
sudo ldconfig
✅ 永久生效
sudo cp libhello.so /usr/lib64/
sudo ldconfig
CentOS 64 位默认库路径:
/usr/lib64
ldd main
示例输出:
libhello.so => /usr/lib64/libhello.so
-fPICrelocation R_X86_64_32 against `.rodata' can not be used
✅ 解决:
g++ -fPIC -c hello.cpp
-lhello → libhello.so
ldd main
查看是否显示 not found
CXX = g++
CXXFLAGS = -fPIC
all: libhello.so main
libhello.so: hello.cpp
$(CXX) $(CXXFLAGS) -c hello.cpp -o hello.o
$(CXX) -shared -o libhello.so hello.o
main: main.cpp
$(CXX) main.cpp -o main -L. -lhello
clean:
rm -f *.o *.so main
✅ CentOS C++ 动态库配置流程
g++ -fPIC -cg++ -shared-L + -lLD_LIBRARY_PATH 或 ld.so.confldconfig如果你是在 CMake / CLion / 实际项目 / 多目录结构 中使用,可以告诉我,我可以给你对应配置示例。