Ubuntu上からrust-sdl2を含んだプロジェクトをwindows向けにコンパイルする

windows向けのターゲットを探す

$ rustup target list | grep win
i586-pc-windows-msvc
i686-apple-darwin
i686-pc-windows-gnu
i686-pc-windows-msvc
x86_64-apple-darwin
x86_64-pc-windows-gnu
x86_64-pc-windows-msvc

今回はx86_64-pc-windows-gnuを使う。ついでにwingw-w64もインストール

$ rustup target add x86_64-pc-windows-gnu
$ sudo apt install mingw-w64

インストールが終了したらビルド。

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

なんかエラーがいっぱい出た。

error: linking with `x86_64-w64-mingw32-gcc` failed: exit code: 1
(略)
= note: /usr/bin/x86_64-w64-mingw32-ld: cannot find -lSDL2
        collect2: error: ld returned 1 exit status

~/.cargo/config に以下のように書けば良いとかいう話が出てきた。


[target.i686-pc-windows-gnu]
linker = "i686-w64-mingw32-gcc"

[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"

再ビルド

 $ cargo build --target x86_64-pc-windows-gnu
error: linking with `x86_64-w64-mingw32-gcc` failed: exit code: 1
(略)
= note: /usr/bin/x86_64-w64-mingw32-ld: cannot find -lSDL2
        collect2: error: ld returned 1 exit status

無駄だった。

エラーをよく見たらSDL2が無いとか言ってるのでインストールしてみる。

# apt-get install -y libsdl2-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
libsdl2-dev is already the newest version (2.0.8+dfsg1-1ubuntu1.18.04.1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

インストール済みだった。

仕方がないので公式からダウンロード、解凍、必要そうなライブラリたちをコピー。 version部分は適宜最新版に変えてほしい。

$ wget https://www.libsdl.org/release/SDL2-devel-2.0.8-mingw.tar.gz
$ tar xvf SDL2-devel-2.0.8-mingw.tar.gz
$ cp -r SDL2-2.0.8/x86_64-w64-mingw32/lib/* ~/.multirust/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-pc-windows-gnu/lib/

再々ビルド。

$ cargo build --target x86_64-pc-windows-gnu
 Finished dev [unoptimized + debuginfo] target(s) in 0.27s

やったぜ。

releaseオプション等をつけてないのでexeファイルは

プロジェクト名/target/x86_64-pc-windows-gnu/debug/プロジェクト名.exe

に配置される。 このexeファイルと先ほど解凍した

SDL2-2.0.8/x86_64-w64-mingw32/bin/SDL2.dll

をwindowsに持っていけば動く。