Open2

emscriptenをビルドする

kokorokokoro

emscriptenのビルドを通じてソースコードの構成や依存ライブラリを眺めながら整理してみる。

本家ドキュメント:https://emscripten.org/docs/building_from_source/

環境

Windows で Visual Studio 付属の Developer Command Prompt for VS 2022 を利用

ビルド

まずは依存物である LLVM と binaryen をビルドする。

LLVM(https://github.com/llvm/llvm-project)

git clone https://github.com/llvm/llvm-project.git
cd llvm-project
cmake -G Ninja -B build -S llvm -DLLVM_ENABLE_PROJECTS="clang;lld;lldb;clang-tools-extra" -DLLVM_TARGETS_TO_BUILD="host;WebAssembly" -DCMAKE_BUILD_TYPE=Release -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_INCLUDE_TESTS=OFF
ninja -C build

binaryen(https://github.com/WebAssembly/binaryen)

WebAssembry のためのコンパイラとツールチェーン一式。
Binaryen IR という軽量を売りにした中間表現を持つ。

git clone https://github.com/WebAssembly/binaryen.git
cd binaryen
git submodule init
git submodule update

なお現時点で依存ライブラリは gtest だけっぽい。

cmake -S . -B build -G Ninja
ninja -C build

ビルド成果物の実行ファイル一覧

cd build/bin
$ find . -name "wasm*.exe"
./wasm-as.exe
./wasm-ctor-eval.exe
./wasm-dis.exe
./wasm-emscripten-finalize.exe
./wasm-fuzz-types.exe
./wasm-metadce.exe
./wasm-opt.exe
./wasm-reduce.exe
./wasm-shell.exe
./wasm-split.exe
./wasm2js.exe

ヘッダファイル
https://github.com/WebAssembly/binaryen/blob/main/src/binaryen-c.h

emscripten(https://github.com/emscripten-core/emscripten)

git clone https://github.com/emscripten-core/emscripten.git
cd emscripten

emscripten は python のスクリプトからなるので特にコンパイル作業はない。
emcc コマンドで .emscripten ファイルを作成し、ビルドした LLVM と binaryen にパスを通す.

emcc --generate-config
.emscripten
LLVM_ROOT=`<checkout_path>\\llvm-project\\build\\bin`
BINARYEN_ROOT=`<checkout_path>\\binaryen\\build`

emcc --check で動作確認できればOK.

$ emcc --check
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.30-git (785bdd9fa781f3e55c77d6f294a6c02c729e49ef)
shared:INFO: (Emscripten: Running sanity checks)
kokorokokoro

emcc(Emscripten Compiler Frontend) の簡単な動作確認

hello_world.c をコンパイルしてみる

https://emscripten.org/docs/building_from_source/verify_emscripten_environment.html

emcc test\hello_world.cでビルドするとカレントディレクトリに次の2つがビルドされる.

  • a.out.js
  • a.out.wasm

node でコンパイルされた a.out.js を実行すると hello world! が出力される。

$ node a.out.js
hello, world!

html を出力することもできる。

emcc test\hello_world.c -o hello.html

ただし手元の Chrome だと emscripten の file:// XHR が動作せず必要なファイルを読み込めない(.wasm) ない。

python -m http.server として local http server を立てて http://localhost:8000/hello.html でHTTP経由でアクセスする(一般的なWeb開発作法)。