Let's Write some C
In a new directory, create a C file:
void say_hello();
int main() {
say_hello();
return 0;
}
Now copy libex03_rust_from_c.so (or .dylib etc) into your C source directory. On Mac/Linux, compile with:
cc rust_from_c.c -o rust_from_c -L. -lex03_rust_from_c
Run ./rust_from_c and it prints "Hello, World from Rust."
On Linux, you may need
LD_LIBRARY_PATH=. ./rust_from_c. Linux doesn't look in the current directory by default!
This is Painful - Automate!
There's a script in the repo "c" directory called build_linux.sh. It makes this a lot easier:
#!/bin/bash
# Setting the CARGO_TARGET_DIR lets you specify where the build will go
CARGO_TARGET_DIR="tmp" cargo build
# Since we know the output, we can copy it
cp tmp/debug/libex03_rust_from_c.so .
# Clean up afterwards!
CARGO_TARGET_DIR="tmp" cargo clean
# Invoke the C compiler
cc rust_from_c.c -o rust_from_c -L. -lex03_rust_from_c
# Run it, including the LD_LIBRARY_PATH
LD_LIBRARY_PATH=. ./rust_from_c