- WebAssembly 教程
- WebAssembly - 主页
- WebAssembly - 概览
- WebAssembly - 介绍
- WebAssembly - WASM
- WebAssembly - 安装
- WebAssembly - 编译为 WASM 的工具
- WebAssembly - 程序结构
- WebAssembly - JavaScript
- WebAssembly - JavaScript API
- WebAssembly - 在 Firefox 中调试 WASM
- WebAssembly - “Hello World”
- 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>
输出
输出如下所示 -
广告