Emscripten
April 27, 2023About 2 min
Emscripten
把c++打包为WebAssembly....
Install
Windows
# 下载工具
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
# 安装 需要科学上网
./emsdk install latest
./emsdk activate latest
# 更新环境变量
./emsdk_env.bat
运行后所有需要的文件都在emsdk/upstream/
文件夹中,需要把emsdk/upstream/bin
设置到环境变量。
值得注意的是:upstream\emscripten\.emscripten
文件记录的是需要使用到的其他模块的执行文件位置。需要手动设置以下两个地方:
# 如果安装了LLVM会自动检测到安装的版本
# 但是推荐这样配置,在upstream中也有llvm的执行文件
# 同时版本也是smsdk匹配的,减少编译警告
LLVM_ROOT = 'D:\\Code\emsdk\\upstream\\bin'
# 在使用该变量时,后面会自动补齐bin\。使用wsam等执行文件
BINARYEN_ROOT = 'D:\\Code\\emsdk\\upstream\\'
最后需要安装MinGW
。
Mac
命令安装:
brew install emscripten
Command
指定编译文件:
# 一种
em++ bgfx.cpp -std=c++11 -O2 -s ALLOW_MEMORY_GROWTH=1 -s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2 -s USE_LIBPING=1 test.cpp -o page.html --preload-file .\assets
# 两种
em++ main.cpp -std=c++11 -s WASM=1 -s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2 -O2 -o main.html
em++ WindowsProject1.cpp -std=c++11 -s WASM=1 -s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2 -O2 -o main.html
Cmake
在使用cmake
命令前加上emcmake
字段,该字段会自动设置编译工具等。如执行以下命令:
emcmake cmake ..
转义后的命令为:
cmake .. -DCMAKE_TOOLCHAIN_FILE=D:\Code\emsdk\upstream\emscripten\cmake\Modules\Platform\Emscripten.cmake "-DCMAKE_CROSSCOMPILING_EMULATOR=C:\Program Files\nodejs\node.exe" -G "MinGW Makefiles"
在CMakeLists.txt
文件中可以设置:
add_executable(${OutputExecutable} ${SOURCE_CXX_FILES})
######################################################################
# Emscripten
######################################################################
if (EMSCRIPTEN)
# Generate an HTML file
set(CMAKE_EXECUTABLE_SUFFIX .html)
# Build Cache: SDL2_mixer, libpng, zlib
execute_process(COMMAND "${EMSCRIPTEN_ROOT_PATH}/embuilder${EMCC_SUFFIX}" build sdl2_mixer libpng zlib)
if(EXISTS "${SOURCE_DATA_DIR}" AND IS_DIRECTORY "${SOURCE_DATA_DIR}")
target_link_options(
${OutputExecutable}
PRIVATE
-sALLOW_MEMORY_GROWTH=1
-sMAX_WEBGL_VERSION=2
-sMIN_WEBGL_VERSION=2
-sUSE_LIBPNG=1
-sUSE_SDL_MIXER=2 # thanks for the s, cstd
-sLLD_REPORT_UNDEFINED
--preload-file ${SOURCE_DATA_DIR}@assets)
else()
target_link_options(
${OutputExecutable}
PRIVATE
-sALLOW_MEMORY_GROWTH=1
-sMAX_WEBGL_VERSION=2
-sMIN_WEBGL_VERSION=2
-sUSE_LIBPNG=1
-sUSE_SDL_MIXER=2 # thanks for the s, cstd
-sLLD_REPORT_UNDEFINED)
endif()
endif() # Emscripten
其中EMSCRIPTEN
字段在Emscripten.cmake文件中定义的。
在vscode中配置
https://blog.evernightfireworks.com/emscripten_config/
Example Project
Project Respiratory: https://github.com/Moros1138/pge-template-project
Refence
https://emscripten.org/index.html