emsripten安装与使用

来源:https://emscripten.org/docs/getting_started/Tutorial.html

1、安装

(1)安装

# Get the emsdk repo
git clone https://github.com/emscripten-core/emsdk.git
# Enter that directory
cd emsdk

# Fetch the latest version of the emsdk (not needed the first time you clone)
git pull
# Download and install the latest SDK tools.
./emsdk install latest
# ./emsdk install 1.38.45
# Make the "latest" SDK "active" for the current user. (writes .emscripten file)
./emsdk activate latest

(2)设置环境

source ./emsdk_env.sh    #linux
emsdk_env.bat    #windows上直接运行.bat

(3)验证

./emcc -v

2、运行Emscripten

(1)在emcc后指定C/C++文件,也可用em++强制执行C++编译。

./emcc tests/hello_world.c

(2)生成两个文件a.out.js和a.out.wasm。.wasm是WebAssembly文件,包含编译生成的代码。.js包含运行时支持,加载和运行.wasm文件。可以用node.js运行它们:

 node a.out.js

3、生成HTML

./emcc tests/hello_world.c -o hello.html

(1)可以在浏览器中打开hello.html。

(2)生成本地网页服务器:Chrome、Safari等浏览器均不支持file://XHR请求,不能加载附加文件.wasm等,需要新建一个本地网页服务器,然后打开:

http://localhost: 8000/hello.html。

python -m http.server 8000

4、访问本地文件

比如网页显示时要显示本地文件夹中的内容,需要同步加载。一般要加载本地文件中的内容跟网页界面显示会是异步操作。

(1)JavaScript通常运行在网页浏览器的沙箱中,不用直接访问本地文件。而Emscripten模拟了一个文件系统(不懂!感觉是编译时加载本地文件内容啊,目前看不是这么回事!)

(2)要访问的文件是Preloaded(embedded)在虚拟文件系统中。编译时(at compile time),Preloading(or embedding)会生成一个虚拟文件系统,对应于当前文件夹。

./emcc tests/hello_world_file.cpp -o hello.html --preload-file tests/hello_world_file.txt

5、优化代码

./emcc -O1 tests/hello_world.cpp
./emcc -O2 tests/hello_world.cpp
原文地址:https://www.cnblogs.com/wllwqdeai/p/15755954.html