cross compiling and statically linking against Rust libraries

Tiago Seco
May 16, 2019 · 3 min read
Image for post
Image for post
Crustaceans are adaptable and can be found in all kinds of environments.

Targets

$ rustup show
Default host: x86_64-unknown-linux-gnu

installed toolchains
--------------------

stable-x86_64-unknown-linux-gnu (default)
nightly-x86_64-unknown-linux-gnu

installed targets for active toolchain
--------------------------------------

i686-pc-windows-gnu
i686-pc-windows-msvc
i686-unknown-linux-gnu
i686-unknown-linux-musl
x86_64-pc-windows-gnu
x86_64-pc-windows-msvc
x86_64-unknown-linux-gnu
x86_64-unknown-linux-musl

active toolchain
----------------

stable-x86_64-unknown-linux-gnu (default)
rustc 1.31.0 (abe02cefd 2018-12-04)

Project Setup

[package]
name = "mylib"
version = "0.1.0"
authors = ["john doe<jdo@csis.dk>"]

[dependencies]
libc = "*"

[lib]
crate-type = ["staticlib"]
extern crate libc;
use libc::uint32_t;

#[no_mangle]
pub extern "C" fn addition(a: uint32_t, b: uint32_t) -> uint32_t {
a + b
}
#include <stdio.h>
#include <stdint.h>

extern "C" {
uint32_t
addition(uint32_t, uint32_t);
}

int main(void) {
uint32_t sum = addition(1, 2);
printf("%u\n", sum);
}
[build]
target="i686-pc-windows-gnu"

Linux binaries

[build]
target="i686-unknown-linux-musl"
$ g++ -m32 -c -o linux_cpp_caller.o caller.cpp
$ g++ -static -m32 linux_cpp_caller.o -o linux_cpp_caller \
-L./target/i686-unknown-linux-musl/debug/ -lmylib

Windows Binaries

[build]
target="i686-pc-windows-gnu"
rustflags = "-C panic=abort"
$ i686-w64-mingw32-g++ -c -o win_cpp_caller.o caller.cpp
$ i686-w64-mingw32-g++ -static win_cpp_caller.o -o win_cpp_caller \
-L./target/i686-pc-windows-gnu/debug/ \
-lmylib \
-ladvapi32 \
-lws2_32 \
-luserenv

Conclusion


CSIS TechBlog

CSIS Security Group software development and security…

Thanks to Martin Lynge Hansen

Tiago Seco

Written by

CSIS TechBlog

CSIS Security Group software development and security research teams are sharing their experiences building systems to detect, monitor and take down malware infrastructure.

Tiago Seco

Written by

CSIS TechBlog

CSIS Security Group software development and security research teams are sharing their experiences building systems to detect, monitor and take down malware infrastructure.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store