Compiling Rust static library and using it in C++:

2019-08-30 23:19发布

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();
}

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

cargo build --lib

(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

Which resulted in the following error :

/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条回答
老娘就宠你
2楼-- · 2019-08-30 23:37

Name mangling in is not standardized, therefore void hello_world_in_rust() might have a different linkage compared to . 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();
查看更多
登录 后发表回答