5

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?

5
  • 2
    Have you tried "cdylib" as the crate-type instead of "dylib"?
    – E_net4
    Commented Mar 7, 2019 at 11:36
  • Same problem with "cdylib"
    – Stefan
    Commented Mar 7, 2019 at 12:26
  • it works for me with gcc 8.2.0 on a mac
    – olivecoder
    Commented Mar 7, 2019 at 14:41
  • 3
    Try putting the -l gcc_linking after the hello.cpp on the gcc command-line.
    – Jmb
    Commented Mar 7, 2019 at 16:11
  • OMG, putting -l gcc_linking after hello.cpp did indeed work. Thank you very much @Jmb
    – Stefan
    Commented Mar 7, 2019 at 17:28

1 Answer 1

0

As @Jmb suggested, the solution was to change the order of arguments to gcc and list the shared library after the C++ file:

gcc -L target/debug hello.cpp -l gcc_linking -o hello
1
  • Next time, use CMake instead ;)
    – jaques-sam
    Commented Apr 13, 2022 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.