Search code examples
crustrust-cargo

CC crate example won't link with the C functions


So I have been trying to get to learn how to use CC in rust, hence I've tried their example, however I fail to make their example compile...

Here's the error message:

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)

The build file:

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

The main file:

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 and bar.c respectively:

#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"

The repo is organized as follows:

dir:
|src:
|| bar.c
|| foo.c
|| build.rs
|| main.rs
|cargo.toml

Solution

  • The build.rs file needs to be in the top-level directory, next to Cargo.toml, and not in the src directory.

    Also note that you have an error in foo.c:

    printf("this is foo\n");