c++ - 编译 Rust 静态库并在 C++ 中使用它 : undefined reference

标签 c++ linker rust static-libraries

我正在尝试用 Rust 编译一个 static 库,然后在我的 C++ 代码中使用它(注意这是关于从 C++ 调用 Rust,而不是相反)。我浏览了所有可以在网上找到的教程,并回答了类似的问题,但我显然做错了什么,尽管我看不到什么。

我为我的问题创建了一个最小示例:

<强>1。 cargo .toml:

[package]
name = "hello_world"
version = "0.1.0"

[lib]
name = "hello_in_rust_lib"
path = "src/lib.rs"
crate-type = ["staticlib"]

[dependencies]

<强>2。库.rs:

#[no_mangle]
pub unsafe extern "C" fn hello_world_in_rust() {
    println!("Hello World, Rust here!");
}

<强>3。 hello_world_in_cpp.cpp :

extern void hello_world_in_rust();

int main() {
    hello_world_in_rust();
}

为了构建库,在我的 rust 目录中运行:

cargo build --lib

(一切顺利) 我继续在我的 C++ 文件夹中运行:

clang++ hello_world_in_cpp.cpp -o hello.out -L ../hello_world/target/release/ -lhello_in_rust_lib

导致以下错误:

/tmp/hello_world_in_cpp-cf3577.o: In function main :

hello_world_in_cpp.cpp:(.text+0x5): undefined reference to hello_world_in_rust()

最佳答案

中进行名称修改未标准化,因此 void hello_world_in_rust() 相比可能具有不同的链接.您可以通过使用 extern "C" 作为函数签名/原型(prototype)的一部分,在两种语言中强制使用相同的 C 链接:

extern "C" void hello_world_in_rust();

关于c++ - 编译 Rust 静态库并在 C++ 中使用它 : undefined reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50229088/

相关文章:

c++ - 变量可以同时声明为静态和外部吗?

c++ - 如何保存字符串并按顺序读/写它们

c++ - 递归地向 vector 添加项目

rust - 为什么 BinaryHeap 需要 Ord?

rust - 创建 Box<dyn Trait> 时如何转换为 dyn Trait

c++ - 更改 wxDataViewCtrl 中的展开/折叠图标

c++ - xerces-c 2.8 : error while loading shared libraries

c - MSFT 构建、cl 和具有跨库依赖关系的链接

c - 即使使用 `noexecstack`,堆栈也是可执行的

rust - mod 和 use 应该如何作用于 rust 的特征?