
- 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>
輸出
輸出如下所示 -

廣告