Rust 与 C、C++ 互相调用:extern C、静态库和动态库

最近把 rust_and_cmake 收成一个小例子,看 Rust 怎么接一份已经用 make 编好的 C 库,以及 C++ 库要怎样才能用同一套写法接上。同一份 C ABI 也可以反过来:C 和 C++ 再去调 cargo 编出来的 Rust 库。Rust 这边没有 build.rs。在这里记录一下。仓库在 commit e37405d1。

一、同一份 C 源码,两个库文件

c/foo.c 里先有一个函数:

// c/foo.c:5-9
void testcall(float value) {
    printf("Hello, world from C! Value passed: %f\n", value);
    /* 接到管道时 stdout 是全缓冲。fflush 让这行马上出现,顺序和调用一致。 */
    fflush(stdout);
}

c/Makefile 用这份源码编出 c/build/libfoo.a 和 c/build/libfoo.so。.a 是 ar rcs 打出来的归档,.so 是 gcc -shared 的共享库。C++ 那一份在 cxx/Makefile,用 g++ 得到 libbar.a 和 libbar.so。

graph LR
    Foo[foo.c] --> MakeC[c/Makefile]
    Bar[bar.cpp] --> MakeX[cxx/Makefile]
    MakeC --> FooLibs[libfoo.a 与 libfoo.so]
    MakeX --> BarLibs[libbar.a 与 libbar.so]
    FooLibs --> Cargo[cargo rustc]
    BarLibs --> Cargo
    Cargo --> Bins[四个 Rust 程序]
    style Foo fill:#87CEEB,stroke:#333,stroke-width:2px
    style Bar fill:#FFD700,stroke:#333,stroke-width:2px
    style Bins fill:#90EE90,stroke:#333,stroke-width:2px

可以看到,make 负责编库,Cargo 负责编 Rust 并做链接。CPU 是 x86_64 还是 arm64,由容器的 --platform 决定,Makefile 不分支。C 和 C++ 反过来调用 Rust 的四个程序放在后面。

静态链接的声明在 static_link/src/main.rs:

// static_link/src/main.rs:6-13
#[link(name = "foo", kind = "static")]
// extern "C" 用 C 的调用约定声明函数,不生成 Rust 名字修饰。
// 块里只有声明。函数体在 c/foo.c。
extern "C" {
    fn testcall(v: f32);
    // *const / *mut 是 C 指针。空指针由 testcall_scale 返回 -1。
    fn testcall_scale(args: *const ScaleArgs, out: *mut f32) -> i32;
}
// static_link/src/main.rs:24-31
fn main() {
    // println! 是宏。编译期展开成往标准输出写格式化文本的代码。
    println!("Hello, world from Rust! (static)");
    // extern 块里的函数调用必须放在 unsafe 里:rustc 不检查 C 侧有没有越界、
    // 空指针或错误的参数类型。
    unsafe {
        testcall(3.14159);
    }

如上所示,extern "C" 块里只有声明,函数体在 foo.c。f32 对应 C 的 float。调用放在 unsafe 里,因为 rustc 不检查 C 那边的指针和参数。extern "C" 表示按目标平台的 C ABI 传参,符号名就是 testcall,不做 Rust 的名字改写23。

#[link(name = "foo", kind = "static")] 让 rustc 在链接时加上 -l static=foo,也就是 libfoo.a4。动态链接那一份把 kind 写成 "dylib",对应 libfoo.so。C++ 库同样写,只是名字换成 bar,函数换成 testcall_cxx:

// dylib_link_cxx/src/main.rs:6-12
#[link(name = "bar", kind = "dylib")]
// extern "C" 按 C ABI 声明函数。C++ 类 PassedValue 不出现在这里。
// 函数体在 cxx/bar.cpp。ScaleArgs 的布局在 c/scale.h。
extern "C" {
    fn testcall_cxx(v: f32);
    fn testcall_scale_cxx(args: *const ScaleArgs, out: *mut f32) -> i32;
}

在 linux/amd64 容器里拿掉 #[link(name = "bar", kind = "dylib")] 再执行 cargo rustc -p dylib_link_cxx -- -L native=.../cxx/build。main.rs 能编成目标文件,链接失败:

rust-lld: error: undefined symbol: testcall_cxx

链接命令里已经有 -L .../cxx/build,没有 -lbar。extern "C" 只声明符号,#[link] 才要求链接器把库拉进来。

三、-L 和 -C

根目录 Makefile 里,-- 后面的参数只传给这个包的 rustc5:

# Makefile:20-33
static_link: libs
	cargo rustc -p static_link -- -L native=$(CURDIR)/c/build

dylib_link: libs
	cargo rustc -p dylib_link -- -L native=$(CURDIR)/c/build

# libbar.a 引用了 libstdc++,但归档文件不会记录这个依赖。
# -C link-arg 追加在链接命令末尾,-lstdc++ 因此排在 libbar.a 后面。
static_link_cxx: libs
	cargo rustc -p static_link_cxx -- -L native=$(CURDIR)/cxx/build -C link-arg=-lstdc++

# libbar.so 在 g++ -shared 时已经依赖 libstdc++.so。
dylib_link_cxx: libs
	cargo rustc -p dylib_link_cxx -- -L native=$(CURDIR)/cxx/build

-L native=目录 给链接器加一条系统库搜索路径,用来找 libfoo.a、libfoo.so 这种库,不是 Rust 的 rlib6。它不指定库名。库名和 static / dylib 来自上面的 #[link]。

-C 是 rustc 的 codegen 选项,形式是 -C 选项=值7。这里的选项是 link-arg:-C link-arg=-lstdc++ 把字符串 -lstdc++ 追加到链接命令末尾,于是它排在 libbar.a 后面。

同一份 Makefile 开头还有 $(MAKE) -C c。那是 Make 自己的参数,表示进入 c/ 再执行 make。它和 rustc 的 -C 不是同一个开关。

四、静态库收进可执行文件,动态库只记名字

链接发生在 cargo rustc 调用链接器的时候。Cargo 不把 .a 或 .so 当作文件拷进产物。

kind = "static" 时,链接器从归档里抽出被引用的目标文件,把 testcall 或 testcall_cxx 的机器码写进可执行文件。这个项目的每个 .a 只有一个目标文件,而 main 调用了它,所以这份代码会进去。跑完之后不再打开那个 .a。

kind = "dylib" 时,可执行文件里记下依赖的库名。.so 仍留在 c/build 或 cxx/build。进程启动时由动态链接器按 LD_LIBRARY_PATH 打开8。

在 linux/amd64 容器里对这两个程序做 ldd:

static_link_cxx    依赖列表里没有 libbar.so,有 libstdc++.so.6
dylib_link_cxx     libbar.so => cxx/build/libbar.so
                   其后还有 libstdc++.so.6
graph TB
    subgraph staticLink [静态链接 libbar.a]
        Obj[bar.o 里的 testcall_cxx] --> Exe[写进可执行文件]
    end
    subgraph dylibLink [动态链接 libbar.so]
        So[libbar.so 留在 cxx/build] --> Name[可执行文件只记下库名]
        Name --> Ld[启动时 ld.so 打开 .so]
    end
    style Exe fill:#90EE90,stroke:#333,stroke-width:2px
    style Name fill:#87CEEB,stroke:#333,stroke-width:2px

static_link_cxx 仍然依赖系统的 libstdc++.so.6。-lstdc++ 链的是共享版 C++ 标准库。静态的那一份只覆盖 bar.cpp 编出来的代码。

五、C++ 从 extern "C" 穿过去

cxx/bar.cpp 里类留在库内,导出函数使用 C 的语言链接9:

// cxx/bar.cpp:8-35
class PassedValue {
public:
    explicit PassedValue(float value) : value_(value) {
        label_ = "Hello, world from C++! Value passed: ";
    }

    void print() const {
        printf("%s%f\n", label_.c_str(), value_);
        fflush(stdout);
    }

private:
    std::string label_;
    float value_;
};

// extern "C" 使用 C 的调用约定,符号名保持 testcall_cxx,不做 C++ 名字改写。
// 这是 Rust 能稳定调用的边界。类、std::string、异常都留在边界里面。
extern "C" void testcall_cxx(float value) {
    try {
        PassedValue passed(value);
        passed.print();
    } catch (const std::exception& error) {
        printf("C++ exception: %s\n", error.what());
    } catch (...) {
        printf("C++ exception\n");
    }
}

label_ = "..." 会调用 std::string 的构造、赋值和析构。catch (const std::exception&) 还要用异常类型信息和栈展开。这些符号的实现在 GCC 的 libstdc++ 里,不在 bar.cpp 里。printf 在 libc,补不上它们。

libbar.a 只是 bar.o 的归档,里面是尚未解析的引用,不会记下对 libstdc++ 的依赖。所以静态链接要在命令末尾加 -lstdc++。libbar.so 由 g++ -shared 生成,g++ 会自己链上 libstdc++,并把 libstdc++.so.6 写进这个 .so 的动态段10。dylib_link_cxx 因此不用再写 -lstdc++。

对 libbar.so 做 nm -D --defined-only,未改写的定义是 testcall_cxx。PassedValue 的构造和 print 仍是改写后的名字,例如 _ZN11PassedValueC1Ef、_ZNK11PassedValue5printEv。Linux 上 GCC 和 Clang 的这套改写记在 Itanium C++ ABI 里11。Rust 不按那份 ABI 去调类,也不让异常跨过 testcall_cxx。

x86_64 上 float 怎么进寄存器,看 System V AMD64 ABI12。arm64 上看 AAPCS6413。.so 的文件格式和动态段看 System V ELF gABI14。

sequenceDiagram
    participant Rust as Rust main
    participant So as libbar.so
    participant Std as libstdc++.so.6
    Rust->>So: testcall_cxx(float)
    So->>Std: std::string 的构造与析构
    So-->>Rust: 正常返回
    Note over So: 异常在 testcall_cxx 里接住

六、用指针传递 ScaleArgs

c/scale.h 里的结构体只有两个字段。C 和 C++ 都包含这份头文件:

// c/scale.h:7-10
typedef struct ScaleArgs {
    float value;
    int times;
} ScaleArgs;

Rust 侧用 #[repr(C)] 按同样的顺序摆放。Linux LP64 上 int 是 32 位,所以 times 写成 i32。两个字段都是 4 字节,中间没有补齐3:

// static_link/src/main.rs:15-22
// #[repr(C)] 按 C ABI 摆放字段,和 c/scale.h 里的 ScaleArgs 相同。
// value 对 float,times 对 int。Linux LP64 上 int 是 32 位,所以用 i32。
// 两个字段都是 4 字节,结构体里没有补齐。
#[repr(C)]
struct ScaleArgs {
    value: f32,
    times: i32,
}

testcall_scale 接收两个指针。任一为空就返回 -1,不去写结果:

// c/foo.c:11-20
/* args、out 都是指针。任一为空就返回 -1,不去写 out。 */
int testcall_scale(const ScaleArgs *args, float *out) {
    if (args == NULL || out == NULL) {
        return -1;
    }
    *out = args->value * (float)args->times;
    printf("Hello, world from C! %f x %d = %f\n", args->value, args->times, *out);
    fflush(stdout);
    return 0;
}

Rust 把结构体的地址和一块 float 的地址传进去:

// static_link/src/main.rs:33-43
    let args = ScaleArgs {
        value: 3.14159,
        times: 2,
    };
    let mut product = 0.0f32;
    // &args 变成 *const ScaleArgs,&mut product 变成 *mut f32。
    let status = unsafe { testcall_scale(&args, &mut product) };
    println!("scale status: {status}, product: {product:.6}");

    let null_status = unsafe { testcall_scale(std::ptr::null(), &mut product) };
    println!("null args status: {null_status}");

如上所示,库把 3.14159 * 2 写回 product。C++ 的 testcall_scale_cxx 做同一件事,类和 std::string 仍然留在 bar.cpp 里面。空指针那次返回 -1。

七、C 和 C++ 调用 Rust 库

方向换过来之后,导出函数写在 rust_lib/src/lib.rs。rust_lib/Cargo.toml 把 crate-type 写成 staticlib 和 cdylib,一次得到 target/debug/librust_lib.a 和 librust_lib.so15:

# rust_lib/Cargo.toml:7-8
[lib]
crate-type = ["staticlib", "cdylib"]
// rust_lib/src/lib.rs:9-28
// #[no_mangle] 让符号名保持 rust_scale,不使用 Rust 自己的改写。
// extern "C" 使用目标平台的 C ABI,C 和 C++ 都能按这个名字调用。
// 这个函数不能 panic 穿出边界。空指针直接返回 -1。
#[no_mangle]
pub extern "C" fn rust_scale(args: *const ScaleArgs, out: *mut f32) -> i32 {
    if args.is_null() || out.is_null() {
        return -1;
    }
    // *const / *mut 解引用要放在 unsafe 里。调用方保证指针指向 ScaleArgs 和 float。
    unsafe {
        let args = &*args;
        let product = args.value * args.times as f32;
        *out = product;
        println!(
            "Hello, world from Rust lib! {:.6} x {} = {:.6}",
            args.value, args.times, product
        );
    }
    0
}

#[no_mangle] 让动态符号表里的名字就是 rust_scale16。C 程序 c/call_rust.c 只声明这个函数,再把 ScaleArgs 的指针传进去:

// c/call_rust.c:5-17
/* rust_scale 的函数体在 rust_lib。这里只有 C ABI 的声明。 */
int rust_scale(const ScaleArgs *args, float *out);

int main(void) {
    ScaleArgs args = {.value = 3.14159f, .times = 2};
    float product = 0.0f;
    int status = rust_scale(&args, &product);
    printf("C called Rust: status %d, product %f\n", status, product);
    fflush(stdout);

    int null_status = rust_scale(NULL, &product);
    printf("C called Rust null: %d\n", null_status);
    fflush(stdout);

C++ 那份是 cxx/call_rust.cpp,声明前加上 extern "C",避免 C++ 再给 rust_scale 改名。std::string 只用在打印前缀上,不传进 Rust。

根目录先 cargo build -p rust_lib,再把库目录传进两个子 Makefile。call_rust 不放进 c/ 和 cxx/ 的 all,编 libfoo、libbar 时还不会去找 Rust 库:

# Makefile:35-41
# crate-type 同时是 staticlib 和 cdylib。
rust_lib:
	cargo build -p rust_lib

call_rust: rust_lib
	$(MAKE) -C c call_rust RUST_LIB_DIR=$(CURDIR)/target/debug
	$(MAKE) -C cxx call_rust RUST_LIB_DIR=$(CURDIR)/target/debug

c/Makefile 里,动态链接用 -l:librust_lib.so,可执行文件只记下 librust_lib.so 这个名字。同目录还有 .a,写成文件名就不会去挑静态库。静态链接把 librust_lib.a 的路径直接写进命令:

# c/Makefile:27-33
# -l:librust_lib.so 指定文件名,避免同目录的 librust_lib.a 被选中。
# 可执行文件只记录 librust_lib.so,运行时靠 LD_LIBRARY_PATH。
$(BUILD)/call_rust: call_rust.c | $(BUILD)
	$(CC) -Wall -o $@ call_rust.c -L $(RUST_LIB_DIR) -l:librust_lib.so

$(BUILD)/call_rust_static: call_rust.c | $(BUILD)
	$(CC) -Wall -o $@ call_rust.c $(RUST_LIB_DIR)/librust_lib.a

cxx/Makefile 用 g++ 做同样两行,产物是 call_rust_cxx 和 call_rust_static。运行动态链接的程序时,scripts/run.sh 把 target/debug 放进 LD_LIBRARY_PATH。

graph LR
    Rs[rust_lib/src/lib.rs] --> Cargo[cargo build -p rust_lib]
    Cargo --> Archive[librust_lib.a]
    Cargo --> Shared[librust_lib.so]
    Archive --> CStatic[call_rust_static]
    Shared --> CDyn[call_rust]
    Archive --> XStatic[C++ 静态调用方]
    Shared --> XDyn[call_rust_cxx]
    style Rs fill:#FFD700,stroke:#333,stroke-width:2px
    style CDyn fill:#90EE90,stroke:#333,stroke-width:2px
    style XDyn fill:#87CEEB,stroke:#333,stroke-width:2px
sequenceDiagram
    participant C as call_rust.c
    participant Rust as rust_scale
    C->>Rust: ScaleArgs 指针与 float 指针
    Rust-->>C: 写回乘积,返回 0
    Note over Rust: 空指针返回 -1,不写 out

librust_lib.a 里还收进了 Rust 标准库,归档本身不记录它还引用了哪些系统库。rustc --print native-static-libs 会列出 -lgcc_s -lutil -lrt -lpthread -lm -ldl -lc。在这个项目的 Debian bookworm 容器里,glibc 是 2.36,gcc 和 g++ 不额外写这些参数,静态链接也能通过并跑起来。动态库那一侧由 cargo 编 librust_lib.so 时已经记下 libgcc_s.so.1 和 libc.so.6。

八、在容器里跑

仓库根目录的 scripts/build.sh 就是执行这份 Makefile。scripts/run.sh 把 c/build、cxx/build 和 target/debug 放进 LD_LIBRARY_PATH,再跑八个程序。

docker build --platform linux/arm64 -t rust-and-cmake:arm64 .
docker build --platform linux/amd64 -t rust-and-cmake:amd64 .
docker run --rm rust-and-cmake:arm64

GitHub Actions 在 ubuntu-24.04 和 ubuntu-24.04-arm 上各做一次 docker build。镜像构建时会跑 build 和 run。commit e37405d 那次两边都打出了这些行17:

Hello, world from C! 3.141590 x 2 = 6.283180
scale status: 0, product: 6.283180
null args status: -1
Hello, world from Rust lib! 3.141590 x 2 = 6.283180
C called Rust: status 0, product 6.283180
C++ called Rust: status 0, product 6.283180
  静态库 动态库
Rust 调用 C/C++ libfoo.a、libbar.a libfoo.so、libbar.so
C/C++ 调用 Rust librust_lib.a librust_lib.so
可执行文件里 用到的机器码 库文件名
运行时 不再打开这个 .a ld.so 打开 .so

References

  1. liweinan,rust_and_cmake commit e37405d — 增加 C 和 C++ 反向调用 Rust 库的例子。同一仓库里,79ecee3 加上 C++ 库,0ab6a6b 加上 ScaleArgs 指针。Rust 库在 rust_lib/src/lib.rs,C 调用方在 c/call_rust.c。 ↩

  2. The Rust Reference,External blocks。extern "C" 使用目标平台的 C ABI。调用这种函数要放在 unsafe 里。 ↩

  3. The Rustonomicon,Foreign Function Interface。说明 Rust 与 C 之间的声明、unsafe 和类型对应。f32 的 C 布局见 The C representation。 ↩ ↩2

  4. The Rust Reference,The link attribute。kind = "static" 链静态库,kind = "dylib" 链共享库。库名 foo 对应 libfoo.a 或 libfoo.so。 ↩

  5. Cargo 手册,cargo rustc。-- 之后的参数只传给正在构建的那个包的 rustc。 ↩

  6. rustc 手册,-L。native 把目录加入系统库搜索路径。-l 才指定库名和 static / dylib。 ↩

  7. rustc 手册,-C 与 link-arg。-C link-arg 把一个参数原样追加到链接器命令末尾。 ↩

  8. Linux man-pages,ld.so(8)。动态链接器按 LD_LIBRARY_PATH 等路径查找共享库。 ↩

  9. C++ 工作草案,dcl.link。extern "C" 指定语言链接,导出的符号名不做 C++ 改写。条目说明见 cppreference: Language linkage。 ↩

  10. System V ABI,Dynamic Section。共享库依赖记在 ELF 动态段。g++ -shared 的链接选项见 GCC Link Options。 ↩

  11. Itanium C++ ABI,C++ ABI。Linux 上 GCC / Clang 的名字改写和异常机制按这份文档实现。libstdc++ 也按它提供 std::string 和 std::exception。 ↩

  12. x86 psABIs,System V AMD64 ABI。该页提供当前 PDF。x86_64 Linux 上 C 函数的参数和返回值按这份处理器补充文档传递。 ↩

  13. ARM,Procedure Call Standard for the Arm 64-bit Architecture (AAPCS64)。arm64 Linux 上的 C 调用约定。 ↩

  14. System V ABI,gABI。.o 与 .so 的 ELF 格式。 ↩

  15. Cargo 手册,The crate-type field。可选值包括 staticlib 和 cdylib。这两种产物给 C 链接器用,说明见 The Rust Reference: Linkage。 ↩

  16. The Rust Reference,The no_mangle attribute。关掉 Rust 的符号名改写,导出的名字保持 rust_scale。 ↩

  17. GitHub Actions,liweinan/rust_and_cmake run 43695311087。linux/amd64 与 linux/arm64 的 docker build 均成功。日志里有 scale status: 0, product: 6.283180,以及 C called Rust 和 C++ called Rust。 ↩