gpt4 book ai didi

c++ - 使用 gcc 链接从 Rust 编译的动态库

转载 作者:太空狗 更新时间:2023-10-29 23:10:46 25 4
gpt4 key购买 nike

我想从 Rust 程序构建动态库并将其链接到现有的 C++ 项目。对于 C++ 项目,我们坚持使用 gcc 进行编译(一个相对较旧的 gcc 4.8.2,但我也在尝试使用 gcc 7.3.0 来解决同样的问题)。

这是该问题的一个最小示例:

源码/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]

你好.cpp:

extern "C" void hello();

int main() {

hello();
return 0;
}

现在,当我使用 clang 链接时,一切正常:

cargo build --lib
clang -L target/debug -l gcc_linking hello.cpp -o hello
LD_LIBRARY_PATH=target/debug:$LD_LIBRARY_PATH ./hello

正如预期的那样,这会导致:

Hello World, Rust here!

但是如果我尝试将其与 gcc 链接,我会收到以下链接错误:

gcc -L target/debug -l gcc_linking hello.cpp -o hello

输出:

/tmp/ccRdGJOK.o: In function `main':
hello.cpp:(.text+0x5): undefined reference to `hello'
collect2: error: ld returned 1 exit status

查看动态库:

# objdump -T output
0000000000043f60 g DF .text 0000000000000043 Base hello
# nm -gC output
0000000000043f60 T hello

我怀疑这个问题与函数名称的混淆有关,但我不知道如何解决它。

有什么想法吗?

最佳答案

正如@Jmb 所建议的,解决方案是更改 gcc 的参数顺序,并在 C++ 文件之后列出共享库:

gcc -L target/debug hello.cpp -l gcc_linking -o hello

关于c++ - 使用 gcc 链接从 Rust 编译的动态库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55042666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com