The aim is to create a function in C and call that function from Rust.
To run C from Rust we first need to compile it to a library. There are two options for this:
- Static library Includes all code, and does not require anything extra from the system, meaning larger file, but more independent. .a file for Linux/MacOs .lib file for Windows
- Dynamic library Requires libraries from the OS, but results in smaller file size. .so for Linux/Unix/Android .dll for Windows .dylib for MacOS
To compile our C code into a .a file, we'll need to run the makefile provided.
cd c_lib
makeThis will create .o files, and a file called libclib.a. This file should always have the naming convention of lib{name}.a. In our case, our library is called clib.
In the file rust_ffi/build.rs we can either tell Rust to look for the library file, or we can tell it how to compile the library file. The current code will compile it when running. Example code of how to point to the library file is as follows
fn main() {
println!("cargo:rustc-link-search=native=../c_lib/");
println!("cargo:rustc-link-lib=clib");
}To actually run rust, we can simply run cargo run in the rust_ffi folder.