Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Calling C++ code from Rust

Start off with some Rust source code :

#[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!");
unsafe {

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 .

... 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