编译Rust静态库并在C ++中使用它:未定义参考 [英] Compiling Rust static library and using it in C++: undefined reference

查看:1122
本文介绍了编译Rust静态库并在C ++中使用它:未定义参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to compile a static library in Rust, and then use it in my C++ code (note this is about calling Rust from C++ and not the other way around). I went over all the tutorials I could find online, and replies to similar questions, and I'm obviously doing something wrong, though I can't see what.

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

I created a minimal example for my problem :

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. lib.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目录中运行:

To build the library, in my rust directory I ran :

货物建造--lib

cargo build --lib

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

(which went fine) I proceeded to run, in my C++ folder :

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

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:在函数main中:

hello_world_in_cpp.cpp :(.text + 0x5):对hello_world_in_rust()的未定义引用

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

推荐答案

.您可以通过使用extern "C"作为函数签名/原型的一部分来在两种语言中强制使用相同的C链接:

Name mangling in c++ is not standardized, therefore void hello_world_in_rust() might have a different linkage compared to c. You can force the same C linkage in both languages by using extern "C" as part of the functions signature/prototype:

extern "C" void hello_world_in_rust();

这篇关于编译Rust静态库并在C ++中使用它:未定义参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆