Thanks @td_ for an excellent question, and to @felixc and @comex for great guidance. I was actually reading the FFI chapter of a Rust book when this was posted, and I decided to have a go at linking a Rust Project with a custom C Library that simply printed out "Hello, World!".
Here's how I got it to work:
- Cargo.toml was updated to use a Build Script in a file named build.rs. The 'links' entry was added to the manifest, stating that that the package links to the 'libhello' native library. I used the gcc-rs Rust Build Library (helpful in invoking gcc as a C compiler for Rust). I read the Build Script link shared by @felixc at http://doc.crates.io/build-script.html. I updated Cargo.toml with a Build Dependency to gcc-rs on GitHub.
[package]
links = "hello"
build = "build.rs"
[build-dependencies.gcc]
git = "https://github.com/alexcrichton/gcc-rs"
Note: As an alternative to using the GitHub link, as described here one may instead add the gcc dependency with:
[build-dependencies]
gcc = "0.3"
- hello.c source code was created in the folder ./src/c/ (relative to the Rust Project root directory)
#include <stdio.h>
void hello() {
printf("Hello, World!\n");
}
- build.rs file was created in the same directory as Cargo.toml with the following contents. I referred to the gcc Crate's Documentation and used the advanced configuration. This gcc Crate compiles the C code contained in hello.c into a Static C Library archive libhello.a (.a extension is an object code archive file):
extern crate gcc;
fn main() {
gcc::Config::new()
.file("src/c/hello.c")
.include("src")
.compile("libhello.a");
}
- main.rs (Crate Root of the Binary Crate) was created in ./src
use std::old_io;
fn main() {
#[link(name="hello", kind="static")]
extern { fn hello(); }
unsafe { hello(); };
}
Running cargo run successfully compiles and prints "Hello, World!" in the terminal.
Note however that for some reason when I pushed this code to GitHub, the Travic CI build failed with error (I do not know how to fix this):
error: linking with `cc` failed: exit code: 1