我正在尝试在Rust中编译一个静态库,然后在我的C++代码中使用它(请注意,这是关于从C++调用Rust而不是相反)。我查看了所有我能在网上找到的教程和类似问题的回答,显然我做错了什么,但我看不出来。
我为我的问题创建了一个最小示例:
1. Cargo.toml:
要构建库,在我的 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()' ```
我为我的问题创建了一个最小示例:
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 目录中运行:
``` 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()' ```
extern "C"
吗? - MB-F