mac wasm 环境搭建 编译自己的fib

原文链接: mac wasm 环境搭建 编译自己的fib

上一篇: mac 上asm wasm js 性能对比

下一篇: js 图片灰度转换 wasm性能对比

https://webassembly.org/

https://medium.com/@tdeniffel/pragmatic-compiling-from-c-to-webassembly-a-guide-a496cc5954b8

https://medium.com/@tdeniffel/c-to-webassembly-pass-and-arrays-to-c-86e0cb0464f5

安装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 脚本

up-2f2f193bbc41110da6b3ae85d38b53aa2dd.png

/Users/ace/.config/fish , 添加函数

up-5becff4cba2ec3462785759c71d8562a311.png

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 \n", 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

添加环境变量

up-cd26816f4d1f945bbbd9160518ea5a8a619.png

编译

➤ emcc -O3 -s WASM=1 -s EXTRA_EXPORTED_RUNTIME_METHODS='["cwrap"]' fib.cpp

拿到的产物可以直接执行

up-044b1618aad5b716dd6d5e8206e9e607377.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值