温馨提示×

ubuntu下c加加怎么连接库

小樊
40
2026-10-19 23:42:57
栏目: 智能运维

在 Ubuntu 下用 C++ 连接(链接)库,一般分为 系统库、第三方库 和 自己写的库,常见流程如下。


一、基本概念

  • 编译(compile):把 .cpp 变成 .o
  • 链接(link):把 .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 → -lpthread
  • libm.so → -lm

三、使用第三方库(如 OpenCV、Boost)

示例:OpenCV

先安装:

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


四、链接自己写的库

1️⃣ 静态库(.a)

写库代码

// 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

2️⃣ 动态库(.so)

生成动态库

g++ -fPIC -shared mylib.cpp -o libmylib.so

使用

g++ main.cpp -L. -lmylib -o main

运行前:

export LD_LIBRARY_PATH=.
./main

五、用 CMake(推荐)

CMakeLists.txt 示例

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

六、常见问题

1. 找不到库

cannot find -lxxx

解决:

  • 确认库已安装
  • 用 -L/path/to/lib

2. 运行找不到 .so

error while loading shared libraries

解决:

export LD_LIBRARY_PATH=/path/to/lib

或:

sudo ldconfig

如果你有 具体库名(比如 MySQL、SQLite、Boost、OpenCV、自己写的库),可以告诉我,我给你写完整示例。

0 踩