How to generate standalone webassembly with emscripten

爷,独闯天下 提交于 2020-01-05 05:11:18

问题


The documentation offers two options: let optimizer strip unnecessary code and then replace the .js glue with your own, or use SIDE_MODULE flag.

Both options result in a memory import (instead of export), and in the case of SIDE_MODULE a ton of extra imports/exports are also defined.

Compare it to a clean output provided by Webassembly Studio:

(module
  (type $t0 (func))
  (type $t1 (func (result i32)))
  (func $__wasm_call_ctors (type $t0))
  (func $main (export "main") (type $t1) (result i32)
    i32.const 42)
  (table $T0 1 1 anyfunc)
  (memory $memory (export "memory") 2)
  (global $g0 (mut i32) (i32.const 66560))
  (global $__heap_base (export "__heap_base") i32 (i32.const 66560))
  (global $__data_end (export "__data_end") i32 (i32.const 1024)))

Here, the memory is exported, and __heap_base is provided, making it easy to write our own allocator. Emscripten output does not export any such values, so we can't know where to start memory allocation.

Is it possible to get similar output with emcc?

Update: it seems that static/stack sizes are determined internally by emcc, and the only way to retrieve them would be by parsing the generated .js file. Side modules are a different beast and I should probably avoid them if I don't actually need relocatable modules.


回答1:


You can simply set the output option (-o) to a filename with the .wasm extension. Emscripten will then output only the wasm file.

So if you have the following test.c file:

#include "emscripten.h"

EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
    return a + b;
}

And you compile it with emscripten like this:

emcc -O3 test.c -o test.wasm

you will only get the file test.wasm and no extra .js file. Also if you disassemble test.wasm using e.g. wasm2wat you'll get this WebAssembly text:

(module
  (type (;0;) (func))
  (type (;1;) (func (param i32 i32) (result i32)))
  (func (;0;) (type 0)
    nop)
  (func (;1;) (type 1) (param i32 i32) (result i32)
    local.get 0
    local.get 1
    i32.add)
  (memory (;0;) 256 256)
  (export "memory" (memory 0))
  (export "add" (func 1))
  (export "_start" (func 0))
  (data (;0;) (i32.const 1536) "\a0\06P"))

as you can see it's just what you would expect from a minimum webassembly binary.



来源:https://stackoverflow.com/questions/52054130/how-to-generate-standalone-webassembly-with-emscripten

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!