mac wasm 环境搭建 编译自己的fib
https://webassembly.org/
安装cmake
brew install cmake
没有brew
https://brew.sh/index_zh-cn
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
https://emscripten.org/docs/getting_started/downloads.html
# 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
# Make the "latest" SDK "active" for the current user. (writes .emscripten file)
./emsdk activate latest
# Activate PATH and other environment variables in the current terminal
source ./emsdk_env.sh
因为每次环境都会失效, 所以可以把这个作为一个函数
emsdk 提供了 fish 脚本
/Users/ace/.config/fish , 添加函数
fib.c
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int fib(int n)
{
int i, t, a = 0, b = 1;
for (i = 0; i < n; i++)
{
t = a + b;
a = b;
b = t;
}
return b;
}
int main()
{
int i;
for (i = 0; i < 10; i++)
printf("hello %d %d", i, fib(1));
return 0;
}
// emcc fib.c -s WASM=1 -s -o fib.html
// emcc fib.cpp -s WASM=1 -s -o fib.html
fib.cpp
#include <emscripten.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C"
{
#endif
int EMSCRIPTEN_KEEPALIVE fib(int n)
{
int i, t, a = 0, b = 1;
for (i = 0; i < n; i++)
{
t = a + b;
a = b;
b = t;
}
return b;
}
int EMSCRIPTEN_KEEPALIVE fibWasm(int n)
{
return n < 2 ? n : fibWasm(n - 1) + fibWasm(n - 2);
}
#ifdef __cplusplus
}
#endif
int main(int argc, char **argv)
{
int i;
for (i = 0; i < 10; i++)
printf("hello %d %d
", i, fib(1));
return 0;
}
// emcc fib.c -s WASM=1 -s -o fib.html
// emcc fib.cpp -s WASM=1 -s -o fib.html
// emcc -O3 -s WASM=1 -s EXTRA_EXPORTED_RUNTIME_METHODS="["cwrap"]" fib.cpp
添加环境变量
编译
➤ emcc -O3 -s WASM=1 -s EXTRA_EXPORTED_RUNTIME_METHODS="["cwrap"]" fib.cpp
拿到的产物可以直接执行