温馨提示×

linux c++怎么生成动态库

小樊
33
2026-10-05 02:18:59
栏目: 编程语言

在 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 动态库命名规范

三、使用动态库

1. 编写测试程序

main.cpp

#include "hello.h"

int main() {
    say_hello();
    return 0;
}

2. 编译可执行文件

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

参数说明:

  • -L.:在当前目录找库
  • -lhello:链接 libhello.so

3. 运行程序

./main

如果报错:

error while loading shared libraries: libhello.so

需要指定库路径:

export LD_LIBRARY_PATH=.
./main

或把 .so 放到 /usr/lib 等系统目录。


四、常用补充说明

查看动态库符号

nm -D libhello.so

查看依赖

ldd main

C++ 名字改编(Name Mangling)

如果库要被 C 或其他语言调用,建议加 extern "C":

extern "C" {
    void say_hello();
}

五、Makefile 示例(可选)

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

如果你需要:

  • CMake 生成 .so
  • 带版本的动态库(libxxx.so.1)
  • C++ 类导出为动态库

可以继续问我。

0 踩