如何将C ++文件编译为WebAssembly? [英] How do I compile a C++ file to WebAssembly?

查看:371
本文介绍了如何将C ++文件编译为WebAssembly?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a simple, self-contained C++ file (math.cpp) like this:

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

我如何将其编译为WebAssembly(数学。 wasm )?

How would I compile it to WebAssembly (math.wasm)?

注意:我正在使用Clang工具链。

Note: I am using the Clang tool-chain.

推荐答案

我发现这个要点非常有用。

基本上,这些步骤是:


  1. (使用 -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD = WebAssembly 构建llvm和clang 5.0.0或更高版本)

  2. 用clang将.cpp源代码编译为llvm位代码:

  1. (build llvm and clang 5.0.0 or above with -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly)
  2. Compile the .cpp soure to llvm bitcode with clang:

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

将位码编译为s-assembly:

Compile the bitcode to s-assembly:

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

使用< a href = https://github.com/WebAssembly/binaryen rel = noreferrer> binaryen 的s2wasm工具来创建.wast文件

Use binaryen's s2wasm tool to create a .wast file

s2wasm math.s> math.wast

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

Use WABT's wast2wasm tool to translate the textual .wast file into binary .wasm:

wast2wasm -o math.wasm math.wast

有些步骤让人觉得多余,但我还没有发现允许快捷方式的工具。 (如果llc可以直接编译为.wasm,或者s2wasm确实创建了二进制.wasm文件,顾名思义,那就太好了。)无论如何,一旦工具链开始运行,它就相对容易了。但是请注意,尚无用于Web汇编的C或C ++标准库。

Some of the steps feel redundant but I have not yet found a tool that allows shortcuts. (It would be nice if llc could compile directly to .wasm, or if s2wasm actually created binary .wasm files as the name suggests.) Anyway, once you got the toolchain running it's relatively painless. Note, however, that there are no C or C++ standard libraries for web assembly yet.

或者,如果您只需要.wasm文件来尝试使用某些功能,则可以获得消除了所有工具链上的麻烦。浏览到 https://mbebenita.github.io/WasmExplorer/ 粘贴您的C / C ++代码,然后下载已编译的.wasm文件。

Alternatively, if you need the .wasm file just for trying out stuff you can get away without all the toolchain trouble. Browse to https://mbebenita.github.io/WasmExplorer/, paste in your C/C++ code, and download the compiled .wasm file.

感谢@noontz和@ LB--指出

Thank you @noontz and @LB-- for pointing out that


实际上,要点中的注释建议您可以跳过二进制并直接编译为来自Clang / LLVM的wasm。我当前正在使用C ++的以下命令行:

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 ++文件编译为WebAssembly?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆