编译C/C++为WebAssembly

编译器安装

若是本身想手动安装,能够参考https://emscripten.orgjavascript

我使用docker来运行,运行命令以下(至关于进入一个已经装好了编译器的linux系统)html

sudo docker run -it -v /tmp:/tmp trzeci/emscripten bash

准备好测试的源代码

假设文件test.c的内容以下java

#include <stdio.h>
#include <emscripten/emscripten.h>

int main(int argc, char ** argv){
    printf("This is main function\n");
}

#ifdef __cplusplus
extern "C" {
#endif

void EMSCRIPTEN_KEEPALIVE show(int argc, char ** argv){
    printf("This is show function\n");
}

#ifdef __cplusplus
}
#endif

编译

emcc test.c -s WASM=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']" -o test.js

编译会生成test.jstest.wasm这2个文件,引用的时候须要放在一块儿linux

HTML引用

<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<button>run c show function</button>
<script type="text/javascript" src="test.js" async></script>
<script type="text/javascript">
document.querySelector('button').addEventListener('click', function(){
    Module.ccall('show', null, null, null);
});
</script>
</body>
</html>

注意

main函数是默认就会被调用的docker

网页项目须要跑在HTTP服务下才能够bash

相关文章
相关标签/搜索