Skip to content

Instantly share code, notes, and snippets.

@Wilfred
Last active January 21, 2021 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wilfred/3079845efa92cb3889a5dc1e8091c46a to your computer and use it in GitHub Desktop.
Save Wilfred/3079845efa92cb3889a5dc1e8091c46a to your computer and use it in GitHub Desktop.
Calling a C function from Rust
[package]
name = "remacs"
version = "0.1.0"
authors = ["Wilfred Hughes <me@wilfred.me.uk>"]
[lib]
crate-type = ["staticlib"]
~/projects/remacs/rust_src $ cargo build --release
Compiling libc v0.2.17
Compiling remacs v0.1.0 (file:///home/wilfred/projects/remacs/rust_src)
note: link against the following native artifacts when linking against this static library
note: the order and any duplication can be significant on some platforms, and so may need to be preserved
note: library: dl
note: library: pthread
note: library: gcc_s
note: library: c
note: library: m
note: library: rt
note: library: util
Finished release [optimized] target(s) in 1.48 secs
~/projects/remacs/rust_src $ gcc -Wall -Wextra -L target/release/ -l remacs demo.c
/tmp/ccuJe0ht.o: In function `main':
demo.c:(.text+0xa): undefined reference to `rust_hello'
collect2: error: ld returned 1 exit status
#include <stdio.h>
void rust_hello();
int main() {
rust_hello();
printf("hello world!\n");
return 0;
}
#[no_mangle]
pub unsafe extern "C" fn rust_hello() {
println!("hello from rust!");
}
@lattice0
Copy link

title is wrong please edit, came from google

@tylerIams
Copy link

title is wrong please edit, came from google

I think I must have been referring to demo.c calling a Rust function from C and ignoring the fact that println was the C fxn he was referring to, not sure why I felt it necessary to make the comment where I did (probably was tired!)... good lookin out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment