3

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

Community
  • 1
  • 1
Shir
  • 267
  • 1
  • 3
  • 10
  • Is this the same issue as in https://stackoverflow.com/q/43866969/3005167? – MB-F May 08 '18 at 08:38
  • @kazemakase unfortunately it isn't, as far as I could see. This is C++, and I tried switching to g++ (instead of clang++), but it had no effect. – Shir May 08 '18 at 08:39
  • 3
    @Shir Intuitively I'd guess C++ or C does not matter.... wait, don't you need to specify `extern "C"` in C++? – MB-F May 08 '18 at 08:43
  • @VTT I tried dynamic libraries (namely - linking with an .so file I created by adding "crate-type = ["dylib"]" to my cargo file. It resulted in the exact same "undefined reference" error on compilation. – Shir May 08 '18 at 08:43
  • @kazemakase OMG. That worked! Thank you. – Shir May 08 '18 at 08:47
  • good to hear :) In that case, I guess we can say that the question is answered [here](https://stackoverflow.com/q/44056461/3005167)? – MB-F May 08 '18 at 08:50
  • @kazemakase I wouldn't say that. It explains why your suggestion works, though. – Shir May 08 '18 at 08:53
  • Possible duplicate of [How can I call C++ functions from library in Rust?](https://stackoverflow.com/questions/24105186/how-can-i-call-c-functions-from-library-in-rust) – Stargateur May 08 '18 at 09:13
  • @Stargateur no, it’s the other way around. This question is about calling a Rust library in C++. – Shir May 08 '18 at 12:38
  • @Shir Oh, you very right, but the answer will be very close. – Stargateur May 08 '18 at 17:55

1 Answers1

4

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();
Mário Feroldi
  • 3,463
  • 2
  • 24
  • 49