c++ - 如何将 C++ 文件编译为 WebAssembly?

标签 c++ webassembly

假设我有一个简单的、自包含的 C++ 文件 (math.cpp),如下所示:

int add(int x, int y) {
  return x + y;
}

如何将其编译为 WebAssembly (math.wasm)?

注意:我使用的是 Clang 工具链。

最佳答案

我找到了 this gist很有帮助。

基本上,步骤如下:

  1. (使用 -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly 构建 llvm 和 clang 5.0.0 或更高版本)
  2. 使用 clang 将 .cpp 源编译为 llvm 位代码:

    clang -emit-llvm --target=wasm32 -Oz math.cpp -c -o math.bc

  3. 将位码编译为 s-assembly:

    llc -asm-verbose=false -o math.s math.bc

  4. 使用binaryen的 s2wasm 工具来创建一个 .wast 文件

    s2wasm math.s > math.wast

  5. 使用WABT的 wast2wasm 工具,用于将文本 .wast 文件转换为二进制 .wasm:

    wast2wasm -o math.wasm math.wast

有些步骤感觉多余,但我还没有找到允许快捷方式的工具。 (如果 llc 可以直接编译为 .wasm,或者如果 s2wasm 顾名思义实际上创建了二进制 .wasm 文件,那就太好了。)无论如何,一旦你运行了工具链,它就相对轻松了。但是请注意,目前还没有用于 Web 汇编的 C 或 C++ 标准库。

或者,如果您需要 .wasm 文件只是为了尝试一些东西,您可以摆脱所有工具链的麻烦。浏览 https://mbebenita.github.io/WasmExplorer/ , paste in your C/C++ code ,并下载编译好的 .wasm 文件。


感谢 @noontz 和 @LB-- 指出这一点

Actually as the comments in the gist suggest you can skip binaryen and compile straight to wasm from Clang/LLVM. I'm currently using the following command line for C++ :

clang++ test.cpp -ObjC++ --compile --target=wasm32-unknown-unknown-wasm \ 
        --optimize=3 --output test.wasm

关于c++ - 如何将 C++ 文件编译为 WebAssembly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45146099/

相关文章:

javascript - 如果缓冲区大小大于 4KB,则 WebAssembly.Compile 在主线程上是不允许的

c++ - "void SomeFunction(int, void*)"是什么意思?

c++ - pImpl 习语 - 将私有(private)类实现放在 cpp 中有什么缺点?

c++ - std::strong_ordering 如何仅适用于零?

c++ - 仅在编辑另一个类后才编译更改

java - 组合使用不同高级语言编程的两个 webassembly 组件

c++ - 使用指令、重载的私有(private)继承?

types - 在 Rust 程序和嵌入式 WebAssembly 运行时之间进行通信的最佳实践是什么?

clang - 如何在wasm中更改导入模块名称 "env"?

c++ - Microsoft Visual C++是否支持WebAssembly作为目标?