You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust FFI绑定C代码链接harfbuzz动态库出现未定义引用报错如何解决

问题原因

你当前的链接错误是因为只将-lharfbuzz传给了编译静态库的cc工具,而静态库编译阶段不会处理第三方依赖的链接逻辑,只有rustc调用ld生成最终可执行文件时才需要链接harfbuzz,但你没有把harfbuzz的链接配置传递给rustc,所以ld找不到harfbuzz的符号。
另外你还存在Rust侧FFI函数签名和C代码不匹配的问题,会导致运行时栈异常。

修复步骤

1. 修改build.rs,传递harfbuzz链接配置给rustc

直接遍历pkg_config返回的harfbuzz配置,把库搜索路径、依赖库都传递给rustc即可,修改后的完整代码如下:

use std::env;
extern crate pkg_config;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    // 探测系统harfbuzz依赖
    let harfbuzz_config = pkg_config::Config::new().probe("harfbuzz").unwrap();

    // 编译自定义C静态库
    cc::Build::new()
        .file("src/c_ffi/myharfbuzz.c")
        .includes(harfbuzz_config.include_paths)
        .compile("myharfbuzz");

    // 传递构建规则给cargo
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=src/c_ffi/myharfbuzz.c");
    
    // 传递harfbuzz的链接配置给rustc
    for path in harfbuzz_config.link_paths {
        println!("cargo:rustc-link-search=native={}", path.to_str().unwrap());
    }
    for lib in harfbuzz_config.libs {
        println!("cargo:rustc-link-lib={}", lib);
    }

    // 链接自定义的myharfbuzz静态库
    println!("cargo:rustc-link-search=native={}", out_dir);
    println!("cargo:rustc-link-lib=static=myharfbuzz");
}

2. 修正Rust侧FFI签名和调用逻辑

你的C代码中example函数只有两个int32_t参数,没有字符串参数,需要把main.rs中对应的部分修改为:

use std::os::raw::c_int;

#[link(name = "myharfbuzz")]
extern "C" {
    fn example(a: c_int, b: c_int);
}

fn main() {
    unsafe {
        example(7, 11);
    }
}

额外提示

你C代码中的hb_ot_var_get_axis_infos调用传入了未初始化的axes_array指针,运行时会触发段错误,建议先根据返回的axis数量申请足够的内存后再调用该函数,该问题不影响当前链接错误的修复。

内容的提问来源于stack exchange,提问作者Tan Kian-teng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 23:12:00