Skip to content

Instantly share code, notes, and snippets.

@BH1SCW
Forked from hempnall/Calling_C_From_Rust.md
Created June 13, 2022 03:27
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 BH1SCW/6be8ca38eae482d9889fdf11dd584503 to your computer and use it in GitHub Desktop.
Save BH1SCW/6be8ca38eae482d9889fdf11dd584503 to your computer and use it in GitHub Desktop.
Calling C++ code from Rust

Start off with some Rust source code

hw.rs :

#[link(name = "extern")]
extern {
	fn hello();
}


fn hw_from_a_fn() {
	println!("Hello World! (from a function)");
}

fn main() {
    // The statements here will be executed when the compiled binary is called

    // Print text to the console
    println!("Hello World!");
    hw_from_a_fn();
	
unsafe {
    hello();
}
}

And some C++ code :

#include <stdio.h>

extern "C" {

void hello() {
    printf("Hello, World!\n");
}

}

Compile the C++ code into a static archive:

$ g++ -c extern.cpp
$ ar rvs libextern.a extern.o

Now compile your Rust-to-C++ program

$ rustc -L . hw.rs

... and run your program ...

$ ./hw
Hello World!
Hello World! (from a function)
Hello, World!
$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment