Skip to content

Instantly share code, notes, and snippets.

@klutzy
Last active August 29, 2015 14:05
Show Gist options
  • Save klutzy/7e708e188c6c1bacf9c6 to your computer and use it in GitHub Desktop.
Save klutzy/7e708e188c6c1bacf9c6 to your computer and use it in GitHub Desktop.
// let's build rust program with msvc linker!
#![feature(intrinsics, lang_items)]
#![no_std]
#![no_main]
// (this is not required for msvc, but for "standard" build.)
#[no_mangle]
pub extern "C" fn rust_stack_exhausted() {}
// /ignore segmented_stack
#[no_mangle]
extern "C" fn __morestack() {}
// llvm injects `call __main()` if target is mingw-like.
// (lib/Target/X86/X86ISelDAGToDAG.cpp)
// on mingw-w64, the symbol is defined in crt/gccmain.c.
// if you forget to pass `--target=i686-pc-windows`, this symbol is needed.
// #[no_mangle]
// extern "C" fn __main() {}
// if `main` symbol is found, msvc guesses this is console application.
// if `WinMain` symbol is found, msvc guesses this is gui one.
// otherwise you have to specify subsystem manually: `link.exe /subsystem:{console,windows}`
// (I define `main` here just because I'm LAZY to pass `/subsystem:console`)
#[no_mangle]
pub extern "C" fn main() {}
// `mainCRTStartup` is default entry point for C/C++ programs.
// I think msvcrt defines this function somewhere..
// well, currently we don't use any C runtime support, so let's define here for ourselves.
// the `mainCRTStartup` name can be changed by `link.exe /entry:<othername>`.
#[no_mangle]
#[allow(non_snake_case_functions)]
pub extern "C" fn mainCRTStartup() {
mymain();
}
fn mymain() {
// user32.dll
extern "system" {
fn MessageBoxA(hWnd: u32, lpText: *const u8, lpCaption: *const u8, uType: u32) -> i32;
}
extern "rust-intrinsic" {
fn transmute<T1, T2>(a: T1) -> T2;
}
let a = "hell\0";
let (b, _): (*const u8, int) = unsafe { transmute(a) };
unsafe {
MessageBoxA(0, b, b, 0);
}
}
// rustc hello.rs --emit=obj --target=i686-pc-windows
// link.exe hello.o user32.lib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment