所以我一直在努力学习如何在rust中使用CC,因此我try 了他们的例子,但我没能让他们的例子编译.

以下是错误消息:

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");
}

#include <stdio.h>
#include <stdint.h>

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

推荐答案

build.rs文件需要位于顶级目录中,紧接着Cargo.toml,而不是src目录中.

另请注意,您在foo.c中有一个错误:

printf("this is foo\n");

C++相关问答推荐

如何在C中只使用一个带双方括号([i][j])访问语法的malloc来分配动态大小的2d数组?

C编译器是否遵循restrict的正式定义?

Can函数指针指向C++中具有不同参数连续性的函数

进程已完成,退出代码为138 Clion

在C语言中,是否可以使枚举数向后计数?

我怎么才能用GCC编译一个c库,让它包含另一个库呢?

在Rust和C之间使用ffi时如何通过 struct 中的[U8;1]成员传递指针

在Apple Silicon上编译x86的Fortran/C程序

为什么此共享库没有预期的依赖项?

在C中包装两个数组?

将变量或参数打包到 struct /联合中是否会带来意想不到的性能损失?

将数组插入数组

理解bzip2的BZ2_解压缩函数中的状态重新分配

为什么电路板被循环删除?

为什么会出现此错误?二进制表达式的操作数无效

如果类型是新的,offsetof是否与typeof一起工作?

在C中使用字符串时是否不需要内存分配?

在C中交换字符串和数组的通用交换函数

C 错误:对 int 数组使用 typedef 时出现不兼容的指针类型问题

在 C/C++ 中原子按位与字节的最佳方法?