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

使用CXX工具为C++项目创建Rust绑定时遭遇未定义符号链接错误

CXX工具为C++项目创建Rust绑定时遭遇未定义符号链接错误

嘿,刚接触C++就尝试用CXX做绑定确实有点挑战,别担心,我帮你梳理下问题所在,咱们一步步解决这个链接错误~

首先看你遇到的undefined symbol: hello_world()错误,核心原因有几个,咱们挨个拆解:

1. 编译脚本遗漏了核心C++实现文件

你的build.rs里只指定了编译src/hello_a.cc,但真正实现hello_world()函数的src/hello.cc没被加入编译流程,导致链接器找不到这个函数的二进制实现,自然会报未定义符号。

2. C++代码里的语法错误

在src/hello.cc里,你写了std::String,但C++标准库中的字符串类型是小写的std::string,大写的String是不存在的——这个问题虽然没直接触发当前的链接错误,但会导致后续编译失败,得先修正。

3. 头文件引用路径冗余

你的头文件里用了"cxx-hello/include/hello.h"这种全路径,其实可以简化,只要让编译器知道去include目录找头文件,直接写文件名就行。

接下来是修改后的各个文件,你可以参考替换:

修改后的build.rs

加入核心实现文件hello.cc,并指定头文件搜索目录:

fn main() {
    cxx_build::bridge("src/ffi.rs")
        .file("src/hello.cc")  // 新增:加入hello_world的实现文件
        .file("src/hello_a.cc")
        .include("include")    // 新增:告诉编译器去include目录找头文件
        .compile("cxx-hello");

    println!("cargo:rerun-if-changed=src/ffi.rs");
    println!("cargo:rerun-if-changed=src/hello.cc");
    println!("cargo:rerun-if-changed=src/hello_a.cc");
    println!("cargo:rerun-if-changed=include/hello.h");
    println!("cargo:rerun-if-changed=include/hello_a.h");
}

修改后的src/hello.cc

修正std::String为标准的std::string,并简化头文件引用:

#include "hello.h"

std::string hello_world() {
    return std::string("Hello World");
}

修改后的include/hello_a.h

简化头文件引用路径:

#pragma once
#include "hello.h"
#include "rust/cxx.h"

rust::String hello_world_adapter();

修改后的src/hello_a.cc

同样简化头文件引用:

#include "hello_a.h"
#include "rust/cxx.h"

rust::String hello_world_adapter() {
    return rust::String(::hello_world());
}

现在你可以尝试运行cargo run,应该就能正常编译并输出From c++: Hello World了~

备注:内容来源于stack exchange,提问作者trewfqeqrt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 11:09:35