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

Rust CXX&CMake绑定C++库时cargo build链接错误排查

解决cxx+cmake编译Rust调用C++库时的链接符号缺失问题

错误详情

执行cargo build时出现链接错误,核心问题是找不到_cxxbridge1$whisper_init符号,同时伴随macOS版本不匹配警告:

ld: warning: object file (/usr/local/lib/libwhisper.a(ggml.c.o)) was built for newer macOS version (12.6) than being linked (12.0)
ld: warning: object file (/usr/local/lib/libwhisper.a(whisper.cpp.o)) was built for newer macOS version (12.6) than being linked (12.0)
  Undefined symbols for architecture x86_64:
    "_cxxbridge1$whisper_init", referenced from:
      whisper_rust::interop::ffi::whisper_init::hbcdc3c0c1120a6a9 in whisper_rust-2cf5d7323dfcdb42.1p80ceksqm40omuj.rcgu.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

相关代码片段

  1. Rust侧cxx桥接代码(interop.rs)
    使用cxx::bridge声明C++交互函数,注释掉whisper_init后可正常构建:
#[cxx::bridge]
pub mod ffi {
    unsafe extern "C++" {
        type whisper_token;
        type whisper_context;

        fn whisper_init(path_model: &CxxString) -> *mut whisper_context; // 此行引发错误
    }
}
  1. C++头文件对应函数声明
struct whisper_context * whisper_init(const char * path_model);
  1. build.rs配置
    负责调用cmake编译C++静态库并告知Rust链接路径:
println!("cargo:rerun-if-changed=src/whisper-cpp/*");
    
let dst = cmake::build("src/whisper-cpp");
println!("cargo:rustc-link-search=native={}", dst.display());
println!("cargo:rustc-link-lib=static=whisper");
  1. CMakeLists.txt配置
cmake_minimum_required(VERSION 3.0)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.9" CACHE STRING "Minimum OS X deployment version")
project(whisper VERSION 0.1.0)

# add compiler flags
set(CMAKE_CC_FLAGS "${CMAKE_CC_FLAGS} -I. -O3 -pthread")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I. -O3 -std=c++11 -pthread")


# platform-dependent compiler flags
...

# add source files
aux_source_directory(. SRC_LIST)

# add library
add_library(${PROJECT_NAME} STATIC ${SRC_LIST})
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION})
set_target_properties(${PROJECT_NAME} PROPERTIES PUBLIC_HEADER "whisper.h")

# install
install(TARGETS ${PROJECT_NAME}
        LIBRARY DESTINATION lib
        PUBLIC_HEADER DESTINATION include)

已尝试的无效操作

  • 清理构建缓存后重新构建
  • 在interop.rs中引入C++头文件
  • 搜索相关解决方案
  • 修改CMake中的CMAKE_OSX_DEPLOYMENT_TARGET版本

最终解决步骤

  1. 更新系统版本:将macOS升级到与静态库构建版本匹配的12.6,消除版本不匹配警告
  2. 重装CMake:使用最新版本的CMake编译C++库,避免构建工具的兼容性问题
  3. 调整build.rs配置:确保Rust优先链接自己通过cmake编译生成的静态库,而非系统路径/usr/local/lib下的旧版本库(例如调整链接顺序或明确指定库的绝对路径)

内容的提问来源于stack exchange,提问作者Federico Lolli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:05:18