# cpp 转 wasm demo ### 一.安装emsdk 工具 ``` 1. git clone https://github.com/emscripten-core/emsdk.git 2. cd esmdk 3. git pull 4. ./emsdk install latest 5. ./emsdk activate latest 6. source ./emsdk_env.sh ``` ### 二.编译 #### 编译成js ``` 1. emcc hello.cpp -s WASM=1 -O3 -o out/hello-emcc.js emcc 代表 Emscripten 编译器; hello.cpp 包含 C/C++ 代码的源文件; -s WASM=1 指定使用 WebAssembly; -O3 代码优化级别; -o out/hello-emcc.js 指定生成包含 wasm 模块所需的全部胶接代码的 JS 文件; ``` #### 编译成wasm ``` 1. emcc hello.cpp -s WASM=1 -O3 -o out/hello-emcc-need-loadjs.wasm 在 out 目录你会发现只生成了 wasm 文件,并没有 js,经过查阅文档发现,上面这个命令隐含了 -s STANDALONE_WASM 的配置 ,实际上触发的是 WebAssembly Standalone build,需要自己写 loader 加载和执行(为了方便会主要采用第一种方式生成,稍后会写一个简单的 loadjs 栗子验证这中编译方式) ``` #### 编译整套html ``` 1. emcc hello.cpp -s WASM=1 -O3 -o out/hello-emcc.html 会生成一个 html 文件和对应的 js 文件以及 wasm 文件,html 需要在 web 服务器中打开,这里具体怎么搭建 web 服务以及如何校验,在这里就不做过多解释,我们主要还是讲一些基础操作,如图,就是通过生成 html 得到的结果。 ```