C++编译 WebAssembly

47 阅读1分钟
  1. 工具链选择Emscripten 先安装emsdk,该工具包含了编译C++为WASM的所有工具,包括编译器

    git clone https://github.com/emscripten-core/emsdk.git
    cd emsdk
    
  2. 克隆后下载安装最新的工具链:

    # windows
    ./emsdk.bat install latest
    ./emsdk.bat activate latest
    # powershell,其他bash使用.bat
    ./emsdk_env.ps1
    
    #linux/masOS
    ./emsdk install latest
    ./emsdk activate latest
    source ./emsdk_env.sh
    

    想要长期使用可配置环境变量

  3. 验证安装

    emcc -v
    
  4. 任意编写一个Hello.cpp

    #include <iostream>
    int main()
    {
        std::cout << "Hello, World from C++ and WASM!" << std::endl;
        return 0;
    }
    
  5. 编译

    emcc hello.cpp -o hello.html
    
  6. 运行

    首先启动一个http服务(在编译好的html位置) python -m http.server 8080 然后在浏览器上打开http://localhost:8080/hello.html 最后得到了:

image.png > 参考:emscripten.org/docs/gettin…