简体   繁体   English

编译C程序时无法链接到Rust编译的库

[英]Unable to link to a Rust-compiled library when compiling a C program

I have been trying to compile and run a minimal example of calling a Rust function from C. However, I keep getting a linker error: 我一直在尝试编译并运行一个从C调用Rust函数的最小示例。但是,我不断收到链接器错误:

$ gcc -L . test.c -ltest
C:\Users\...\AppData\Local\Temp\ccWuOBbj.o:test.c:(.text+0x16): undefined reference to `squared'
collect2.exe: error: ld returned 1 exit status

The C code: C代码:

#include <stdio.h>

int squared(int);

int main() {
    printf("5 * 5 = %d", squared(5));
    return 0;
}

The Rust code: Rust代码:

#![no_std]
#![feature(lang_items)]

extern crate core;

#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }

#[no_mangle]
pub extern "C" fn squared(x: isize) -> isize {
    x * x
}

I am compiling the Rust code with rustc --crate-type staticlib -o libtest.a test.rs 我正在用rustc --crate-type staticlib -o libtest.a test.rs编译Rust代码

Some details: 一些细节:

Put "-ltest" after "test.c". “ test.c” 之后放置“ -ltest”。 ld only links in required parts of library archives, and doesn't know squared() is required until it sees the .o file generated from test.c, at which time libtest.a has already been linked earlier when no functions were yet required from it. ld仅链接库档案的必需部分,并且直到看到test.c生成的.o文件时才知道squared()是必需的,此时libtest.a早已链接,当时还不需要任何功能从中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM