From 930924cdf581f403cc62aa61d91c759faa60f6f6 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 19 Apr 2015 10:28:20 -0700 Subject: [PATCH] Add C to Rust example --- c-to-rust/Cargo.toml | 8 ++++++++ c-to-rust/Makefile | 18 ++++++++++++++++++ c-to-rust/src/lib.rs | 6 ++++++ c-to-rust/src/main.c | 11 +++++++++++ 4 files changed, 43 insertions(+) create mode 100644 c-to-rust/Cargo.toml create mode 100644 c-to-rust/Makefile create mode 100644 c-to-rust/src/lib.rs create mode 100644 c-to-rust/src/main.c diff --git a/c-to-rust/Cargo.toml b/c-to-rust/Cargo.toml new file mode 100644 index 0000000..e00dfb6 --- /dev/null +++ b/c-to-rust/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "c-to-rust" +version = "0.1.0" +authors = ["Alex Crichton "] + +[lib] +name = "double_input" +crate-type = ["staticlib"] diff --git a/c-to-rust/Makefile b/c-to-rust/Makefile new file mode 100644 index 0000000..d39910e --- /dev/null +++ b/c-to-rust/Makefile @@ -0,0 +1,18 @@ +all: target/double + target/double + +target: + mkdir -p $@ + +target/double: target/main.o target/libdouble_input.a + $(CC) -o $@ -Wl,--gc-sections $^ -lpthread + +target/libdouble_input.a: src/lib.rs Cargo.toml + cargo build + (cd target && ln -nsf debug/libdouble_input-*.a libdouble_input.a) + +target/main.o: src/main.c | target + $(CC) -o $@ -c $< + +clean: + rm -rf target diff --git a/c-to-rust/src/lib.rs b/c-to-rust/src/lib.rs new file mode 100644 index 0000000..ae41d1f --- /dev/null +++ b/c-to-rust/src/lib.rs @@ -0,0 +1,6 @@ +#![crate_type = "staticlib"] + +#[no_mangle] +pub extern fn double_input(input: i32) -> i32 { + input * 2 +} diff --git a/c-to-rust/src/main.c b/c-to-rust/src/main.c new file mode 100644 index 0000000..ae7bef3 --- /dev/null +++ b/c-to-rust/src/main.c @@ -0,0 +1,11 @@ +#include +#include + +extern int32_t double_input(int32_t input); + +int main() { + int input = 4; + int output = double_input(input); + printf("%d * 2 = %d\n", input, output); + return 0; +}