I'd like to build a dynamic library from a Rust program and link it to an existing C++ project. For the C++ project, we are stuck on using gcc for compilation (a relatively old gcc 4.8.2, but I'm also trying with gcc 7.3.0 with the same issue).
This is a minimal example of the issue:
src/lib.rs
#[no_mangle]
pub unsafe extern "C" fn hello() {
println!("Hello World, Rust here!");
}
Cargo.toml
[package]
name = "gcc-linking"
version = "0.1.0"
authors = ..
edition = "2018"
[lib]
crate-type = ["dylib"]
[dependencies]
hello.cpp:
extern "C" void hello();
int main() {
hello();
return 0;
}
Now, when I link with clang
, everything is fine:
cargo build --lib
clang -L target/debug -l gcc_linking hello.cpp -o hello
LD_LIBRARY_PATH=target/debug:$LD_LIBRARY_PATH ./hello
As expected, this results in:
Hello World, Rust here!
But if I try to link this with gcc
, I get the following linking error:
gcc -L target/debug -l gcc_linking hello.cpp -o hello
Output:
/tmp/ccRdGJOK.o: In function `main':
hello.cpp:(.text+0x5): undefined reference to `hello'
collect2: error: ld returned 1 exit status
Looking at the dynamical library:
# objdump -T output
0000000000043f60 g DF .text 0000000000000043 Base hello
# nm -gC output
0000000000043f60 T hello
I suspect the problem has something to do with mangling of function names, but I cannot figure out how to solve it.
Any ideas?
crate-type
instead of "dylib"?-l gcc_linking
after thehello.cpp
on the gcc command-line.-l gcc_linking
afterhello.cpp
did indeed work. Thank you very much @Jmb