在 Ubuntu 下用 C++ 连接(链接)库,一般分为 系统库、第三方库 和 自己写的库,常见流程如下。
.cpp 变成 .o.o 和库文件(.a / .so)合并成可执行文件库分两种:
.a(编译时拷贝进程序).so(运行时加载)pthread 和 math 库// test.cpp
#include <pthread.h>
#include <cmath>
#include <iostream>
int main() {
std::cout << sqrt(16) << std::endl;
return 0;
}
编译:
g++ test.cpp -o test -lpthread -lm
说明:
-l 后面是库名(去掉 lib 和扩展名)libpthread.so → -lpthreadlibm.so → -lm先安装:
sudo apt install libopencv-dev
代码:
#include <opencv2/opencv.hpp>
int main() {
cv::Mat img;
return 0;
}
编译:
g++ test.cpp -o test `pkg-config --cflags --libs opencv4`
pkg-config自动帮你加-I和-L -l
写库代码
// mylib.cpp
#include <iostream>
void hello() {
std::cout << "Hello Library" << std::endl;
}
// mylib.h
void hello();
生成静态库
g++ -c mylib.cpp -o mylib.o
ar rcs libmylib.a mylib.o
使用库
// main.cpp
#include "mylib.h"
int main() {
hello();
}
编译:
g++ main.cpp -L. -lmylib -o main
生成动态库
g++ -fPIC -shared mylib.cpp -o libmylib.so
使用
g++ main.cpp -L. -lmylib -o main
运行前:
export LD_LIBRARY_PATH=.
./main
cmake_minimum_required(VERSION 3.10)
project(test)
find_package(OpenCV REQUIRED)
add_executable(test main.cpp)
target_link_libraries(test ${OpenCV_LIBS})
构建:
mkdir build && cd build
cmake ..
make
cannot find -lxxx
解决:
-L/path/to/liberror while loading shared libraries
解决:
export LD_LIBRARY_PATH=/path/to/lib
或:
sudo ldconfig
如果你有 具体库名(比如 MySQL、SQLite、Boost、OpenCV、自己写的库),可以告诉我,我给你写完整示例。