CC 箱示例不会与 C 函数链接

问题描述 投票:0回答:1

所以我一直在尝试学习如何在 Rust 中使用 CC,因此我尝试了他们的示例,但是我无法编译他们的示例...

这是错误消息:

error: linking with `cc` failed: exit status: 1

  = note: /usr/bin/ld: /home/usr/MAIN_DIR/dir/target/debug/deps/dir-c24b87d5163d50b4.31veb4gx0s10h8ys.rcgu.o: in function `dir::call':
          /home/usr/MAIN_DIR/dir/src/main.rs:8: undefined reference to `bar_function'
          /usr/bin/ld: /home/usr/MAIN_DIR/dir/src/main.rs:9: undefined reference to `foo_function'
          collect2: error: ld returned 1 exit status
          
  = note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
  = note: use the `-l` flag to specify native libraries to link
  = note: use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib)

构建文件:

fn main() {
    cc::Build::new()
        .file("src/foo.c")
        .file("src/bar.c")
        .compile("foo");
}

主要文件:

extern "C" {
    fn bar_function(x: i32) -> i32;
    fn foo_function();
}

pub fn call() {
    unsafe {
        bar_function(50);
        foo_function();
    }
}


fn main() {
    call()
}

foo.c 和 bar.c 分别:

#include <stdio.h>

void foo_function(void) {
    printf("this is foo\n", num);
}

int32_t bar_function(int32_t x) {
    printf("this is bar: %d\n", x);
    return x;
}

cargo.toml:

[package]
name = "dir"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[build-dependencies]
cc = "1.0"

回购协议的组织方式如下:

dir:
|src:
|| bar.c
|| foo.c
|| build.rs
|| main.rs
|cargo.toml
c rust rust-cargo
1个回答
0
投票

build.rs
文件需要位于顶级目录中,位于
Cargo.toml
旁边,而不是位于
src
目录中。

另请注意,

foo.c
中存在错误:

printf("this is foo\n");
© www.soinside.com 2019 - 2024. All rights reserved.