Introduction to WebAssembly of C++

related resources

Help documentation used by webassembly

emscribe

download and install

# 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 install

The general examples on the Internet are all done directly with em++. This method is only used to write test examples for getting started, and it is not representative

mingw-64 installation

The C++ program used to compile webassembly can also be compiled with nmake on the Internet, but after all, webassembly is similar to the linux environment, and it is more reliable to use mingw-64 to compile (for windows code in the code)

The easiest way to install the above two environments is to install the qt program, select the custom installation inside, check the cmake and mingw64 versions, and get the relevant paths into the environment variables after the installation is complete. For example, the qt6.2 version I installed

image.png

C++ example

  1. Write cmake project files
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;
}

generate compile

#启动cmd 执行emsdk中的emsdk_env.bat之后,切换到当前CMakeLists.txt 
mkdir em
cd em 
emcmake cmake ..
emmake make 

image.png
The example.js and example.wasm files are generated in the generation directory

write html file

<!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>

run start

## 不能直接打开index.html
emrun --no_browser --port 8080 .

Enter 127.0.0.1:8080 in the browser, press F12, open developer debugging
image.png

Guess you like

Origin blog.csdn.net/qq_33377547/article/details/124770415