GithubHelp home page GithubHelp logo

cpp2wasm's Introduction

把 C/C++ 编译成 WebAssembly

参考文章:《从零开始把 C/C++ 编译成 WebAssembly》

源代码

./
 ├── fib.c    # 斐波那契函数
 └── hello.c  # 输出 Hello World!

编译代码

首先安装依赖:

  1. Emscripten
  2. wasi-sdk
  3. WABT (WebAssembly Binary Toolkit)

然后执行下方命令即可编译所有代码,具体每行命令的含义,参考文件内的注释。

./build.sh

测试代码

首先安装 Node.js ,然后在当前目录下执行 npm install,然后就可以执行如下测试:

1. 测试 hello.c

node test-hello.js

将会得到两行输出,分别由 Emscripten 和 wasi-sdk 编译而来:

Hello World!
Hello World!

2. 测试 fib.c

node test-fib.js

将会得到两行输出:

[emcc] fib(3) = 2
[wasi] fib(3) = 2

可以在命令后指定要计算的数字:

node test-fib.js 17

输出:

[wasi] fib(17) = 1597
[emcc] fib(17) = 1597

使用独立运行时

可以使用独立的 WebAssembly 运行时执行编译出来的代码,以 Wasmtime 为例:

# 输出 Hello World!
wasmtime out/hello-wasi.wasm
# 调用 wasi-sdk 编译出来的 fib 函数
wasmtime out/fib-wasi.wasm --invoke fib 8
# 调用 Emscripten 编译出来的 fib 函数
wasmtime out/fib-emcc.wasm --invoke _fib 11

cpp2wasm's People

Contributors

hanks10100 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.