假设我有一个简单的、自包含的 C++ 文件 (math.cpp
),如下所示:
int add(int x, int y) {
return x + y;
}
如何将其编译为 WebAssembly (math.wasm
)?
注意:我使用的是 Clang 工具链。
最佳答案
我找到了 this gist很有帮助。
基本上,步骤如下:
- (使用
-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly
构建 llvm 和 clang 5.0.0 或更高版本) 使用 clang 将 .cpp 源编译为 llvm 位代码:
clang -emit-llvm --target=wasm32 -Oz math.cpp -c -o math.bc
将位码编译为 s-assembly:
llc -asm-verbose=false -o math.s math.bc
使用binaryen的 s2wasm 工具来创建一个 .wast 文件
s2wasm math.s > math.wast
使用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/