LoginSignup
6
5

More than 3 years have passed since last update.

Rust, Ubuntu で Windows 向けに SDL2 アプリをビルドする

Last updated at Posted at 2020-07-29

概要

Ubuntu (WSL) で Windows 用の GUI アプリを Rust で作りたかったので、 SDL2 を動かすまでのメモです。

コンパイルターゲットを追加

rustup で windows 用のツールチェインを追加。

$ rustup target add x86_64-pc-windows-gnu

windows 用のリンカをインストール

$ sudo apt install mingw-w64

SDL の準備

SDL のサイト https://www.libsdl.org/download-2.0.php から SDL2-devel-2.0.12-mingw.tar.gz をダウンロード

$ tar xf SDL2-devel-2.0.12-mingw.tar.gz
$ cp -r SDL2-2.0.12/x86_64-w64-mingw32/lib/* ~/.rustup/toolchains/stable-x86_64-unknown-linux-
gnu/lib/rustlib/x86_64-pc-windows-gnu/lib/

プロジェクトを作る

$ cargo new mysdl
$ cd mysdl

Cargo.toml はこちら。

Cargo.toml
...
[dependencies]
sdl2 = "0.32"

使用するリンカを指定するために、mysdl/.cargo/config ファイルを作る。中身は以下。

mysdl/.cargo/config
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"

main.rs は適当にこんな感じ。

mysdl/src/main.rs
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use std::time::Duration;
use std::thread;

fn main() {
    let sdl_ctx = sdl2::init().unwrap();
    let video_subsys = sdl_ctx.video().unwrap();
    let window = video_subsys.window("SDL2", 640, 480)
        .position_centered()
        .build()
        .unwrap();
    let mut canvas = window.into_canvas()
        .build()
        .unwrap();
    let mut event_pump = sdl_ctx.event_pump().unwrap();

    'running: loop {
        canvas.set_draw_color(Color::RGB(0, 255, 0));
        canvas.clear();
        canvas.present();

        for ev in event_pump.poll_iter() {
            match ev {
                Event::Quit {..} |
                Event::KeyDown {keycode: Some(Keycode::Escape), ..} =>
                    break 'running,
                _ => {}
            }
        }
        thread::sleep(Duration::new(0, 1_000_000_000u32 / 60));
    }
}

ビルド

cargo build --target x86_64-pc-windows-gnu --release

ビルドに成功すれば、mysdl/target/x86_64-pc-windows-gnu/release/mysdl.exe に実行ファイルが生成されます。

SDL2.dll を入手

SDL のサイト https://www.libsdl.org/download-2.0.php から SDL2-2.0.12-win32-x64.zip をダウンロードします。
解凍すると SDL2.dll があります。

実行

ビルドした mysdl.exeSDL2.dll を同じディレクトに置いて mysdl.exe を実行すると動きます。
黄緑色のウィンドウが出ます。閉じるボタンか Esc キーで閉じることができれば成功です。

お疲れさまでした。:coffee:

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5