Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

How do I compile a C++ file to WebAssembly?

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

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

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

Note: I am using the Clang tool-chain.

question from:https://stackoverflow.com/questions/45146099/how-do-i-compile-a-c-file-to-webassembly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found this gist to be very helpful.

Basically, this are the steps:

  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

  3. Compile the bitcode to s-assembly:

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

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

    s2wasm math.s > math.wast

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

    wast2wasm -o math.wasm math.wast

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.

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.


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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...