Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .c source files with Rust

Tags:

rust

Is there a standard way to include .c source files?

So far I've been using extern "C" { ... } to expose the functions, compiling .c to an object file, running rustc until ld chokes with an undefined reference, and using the arguments shown after error: linking with 'cc' failed with code 1; note: cc arguments: ... to run cc myobjfile.o ...

like image 726
eleofw Avatar asked Mar 18 '13 22:03

eleofw


People also ask

Can I use C libraries in Rust?

Rust can generate C dynamic libraries ( . so files) as well as static libraries ( . a files), which can be easily wrapped in Go bindings and Python bindings and used in code written in those languages. You can refer to the full code of the C library written in Rust in the clib folder of the GitHub repository.

Can you import .C files?

You can properly include . C or . CPP files into other source files.

Does C build Rust?

Interface with C and C++Rust has a foreign function interface (FFI) that can be used both to call code written in languages such as C from Rust and to call Rust code from those languages. Rust also has a library, CXX, for calling to or from C++.

Can Rust run C++?

Rust can link to/call C functions via its FFI, but not C++ functions.


2 Answers

Editor's note: This answer predates Rust 1.0 and is no longer applicable.

Luqman gave a hint on IRC; using extern "C" { ... } with #[link_args="src/source.c"]; in the crate file works for me.

like image 134
eleofw Avatar answered Sep 16 '22 23:09

eleofw


Use the cc crate in a build script to compile the C files into a static library and then link the static library to your Rust program:

Cargo.toml

[package]
name = "calling-c"
version = "0.1.0"
authors = ["An Devloper <[email protected]>"]
edition = "2018"

[build-dependencies]
cc = "1.0.28"

build.rs

use cc;

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

src/example.c

#include <stdint.h>

uint8_t testing(uint8_t i) {
  return i * 2;
}

src/main.rs

extern "C" {
    fn testing(x: u8) -> u8;
}

fn main() {
    let a = unsafe { testing(21) };
    println!("a = {}", a);
}
like image 29
Shepmaster Avatar answered Sep 20 '22 23:09

Shepmaster