- WebAssembly 教程
- WebAssembly - 主页
- WebAssembly - 概述
- WebAssembly - 简介
- WebAssembly-WASM
- WebAssembly - 安装
- WebAssembly - 编译为 WASM 的工具
- WebAssembly - 程序结构
- WebAssembly - JavaScript
- WebAssembly - Javascript API
- WebAssembly - 在 Firefox 中调试 WASM
- WebAssembly - “你好世界”
- WebAssembly - 模块
- WebAssembly - 验证
- WebAssembly - 文本格式
- WebAssembly - 将 WAT 转换为 WASM
- WebAssembly - 动态链接
- WebAssembly - 安全
- WebAssembly - 使用 C
- WebAssembly - 使用 C++
- WebAssembly - 使用 Rust
- WebAssembly - 使用 Go
- WebAssembly - 使用 Nodejs
- WebAssembly - 示例
- WebAssembly 有用资源
- WebAssembly - 快速指南
- WebAssembly - 有用的资源
- WebAssembly - 讨论
WebAssembly - 使用 C
在本章中,我们将把一个简单的 C 程序编译为 JavaScript 并在浏览器中执行。
例如 - C 程序
#include<stdio.h>
int square(int n) {
return n*n;
}
我们已经在 wa/ 文件夹中完成了 emsdk 的安装。在同一文件夹中,创建另一个文件夹 cprog/ 并将上述代码保存为 square.c。
我们在上一章已经安装了emsdk。这里,我们将使用emsdk来编译上面的c代码。
在命令提示符下编译 test.c,如下所示 -
emcc square.c -s STANDALONE_WASM –o findsquare.wasm
emcc 命令负责编译代码并为您提供 .wasm 代码。我们使用了 STANDALONE_WASM 选项,该选项仅提供 .wasm 文件。
示例 - findsquare.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WebAssembly Square function</title>
<style>
div {
font-size : 30px; text-align : center; color:orange;
}
</style>
</head>
<body>
<div id="textcontent"></div>
<script>
let square; fetch("findsquare.wasm").then(bytes => bytes.arrayBuffer())
.then(mod => WebAssembly.compile(mod)) .then(module => {
return new WebAssembly.Instance(module)
})
.then(instance => {
square = instance.exports.square(13);
console.log("The square of 13 = " +square);
document.getElementById("textcontent").innerHTML = "The square of 13 = " +square;
});
</script>
</body>
</html>
输出
输出如下 -
