相关资源
Emscripten
下载和安装
# Get the emsdk repo
git clone https://github.com/emscripten-core/emsdk.git
# Enter that directory
cd emsdk
# Fetch the latest version of the emsdk (not needed the first time you clone)
git pull
# Download and install the latest SDK tools. 可能需要代理才能下载,有时候多弄几次也行。
./emsdk install latest
# Make the "latest" SDK "active" for the current user. (writes .emscripten file)
./emsdk activate latest
# Activate PATH and other environment variables in the current terminal
# Windows 下运行emsdk_env.bat 如果没有在环境变量里面设置,那么每次启动的时候都需要调用这个。
emsdk_env.bat
cmake 安装
网上的一般例子都是直接用em++来做,这种方式只是用来编写做入门的测试例子,并没有什么代表性
mingw-64 安装
用于编译webassembly的c++程序,网上也有用nmake来编译的,但毕竟webassembly是类似于linux环境,使用mingw-64 编译更可靠(对于代码中有windows代码来说)
上面两个环境的安装最简单的办法就是安装qt程序,选择里面的自定义安装,勾选cmake 和 mingw64的版本 ,安装完成之后将其相关路径弄到环境变量中。如我安装的qt6.2版本
C++示例
- 编写cmake 工程文件
cmake_minimum_required(VERSION 3.4.1)
project(example CXX)
set(lib_name "example")
add_executable(${lib_name} main.cpp)
target_link_libraries(${lib_name})
# EXIT_RUNTIME=1 表示运行完main函数需要退出运行时。类似于em++ 编译时需要指定的参数
set_target_properties(${lib_name} PROPERTIES LINK_FLAGS "-s EXIT_RUNTIME=1")
#include <stdio.h>
#include <emscripten.h>
int main(int argc, char *argv[])
{
printf("hello world");
return 0;
}
生成编译
#启动cmd 执行emsdk中的emsdk_env.bat之后,切换到当前CMakeLists.txt
mkdir em
cd em
emcmake cmake ..
emmake make
在生成目录下生成了example.js 和example.wasm文件
编写html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<canvas id=foo width=300 height=300></canvas>
//引用刚才生成的example.js文件
<script src="example.js"></script>
<script>
Module.onRuntimeInitialized = function() {
//调用c++封装的函数,main函数会在加载的时候自动运行。如果在这个里面再次调用,会出现调用两次
Module._main();
}
</script>
<body>
<p>this is a example</p>
</body>
</html>
运行启动
## 不能直接打开index.html
emrun --no_browser --port 8080 .
在浏览器中输入127.0.0.1:8080,按F12,打开开发者调试