1

I want to use WebAssembly, so i have to compile C file to WASM file.

The contents of the C file are as follows

//The online 'add.c'
WASM_EXPORT
int add(int a, int b)
{ 
    return a + b;
}

It's a very simple C file.

This WASM file is compiled by Online compilation tools WebAssembly Studio. I use a tool "wasm2wat" to disassembly it to Text file, and the contents are as follows

(module
 (type $t0 (func))
 (type $t1 (func (param i32 i32) (result i32)))
 (func $__wasm_call_ctors (type $t0))
 (func $add (type $t1) (param $p0 i32) (param $p1 i32) (result i32)
   local.get $p1
   local.get $p0
   i32.add)
 (table $T0 1 1 funcref)
 (memory $memory 2)
 (global $g0 (mut i32) (i32.const 66560))
 (global $__heap_base i32 (i32.const 66560))
 (global $__data_end i32 (i32.const 1024))
 (export "memory" (memory 0))
 (export "__heap_base" (global 1))
 (export "__data_end" (global 2))
 (export "add" (func $add)))

And I also use "emcc add.c -s WASM=1 -O3 -o add.js" to compile the local "add.c"

//The local 'add.c'
EMSCRIPTEN_KEEPALIVE
int add(int a, int b)
{
    return a + b;
}

The WASM file obtained from the above command is

(module
 (type $t0 (func))
 (type $t1 (func (param i32 i32) (result i32)))
 (func $b (type $t0)
   nop)
 (func $c (type $t1) (param $p0 i32) (param $p1 i32) (result i32)
   local.get $p0
   local.get $p1
   i32.add)
 (table $a 1 1 funcref)
 (export "a" (table 0))
 (export "b" (func $b))
 (export "c" (func $c)))

Why are the two results different?Why can the above file be used in HTML, but not the following one?

Aves_LH
  • 11
  • 2

1 Answers1

0

Those are two slightly different compiler drivers (although both based on llvm+clang) and they target slight different environments. The ABI/API/contract with the embedder is different in a few ways. For example, in emscripten the default contract is that the WebAssembly memory object is created in JS and export into the WebAssembly file. The default for WASI (wasm outside the web) is to create the memory object in the wasm file and export it to the embedder (hence the "memory" export in your first case).

Some of those superfluous elements in your first example would probably be eliminated by running wasm-opt on the resulting output. For example, if your tiny example neither the memory nor the table is used so in theory both of those can be removed completely.

sbc100
  • 2,619
  • 14
  • 11
  • I see. But why can the above file be used in HTML, but not the following one?The wasm file compiled on the web page can be used in JS, but the wasm compiled locally with "emcc" will report an error. Why? And how can I use "emcc" tool to compile wasm file correctly in JS? – Aves_LH Nov 14 '20 at 05:50