Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Compiling a C program with Emscripten and using the resulting file in vanilla JavaScript involves several steps. Here’s a straightforward process:
- 1. Install Emscripten
- First, you need to install Emscripten. Follow these steps:
- Download and Install Emscripten:
- Go to the Emscripten official site and follow the installation instructions.
- Ensure you have Python and Git installed as prerequisites.
- 2. Write Your C Program
- Create a simple C program, for example, hello.c:
- c
- Αντιγραφή κώδικα
- #include <stdio.h>
- int main() {
- printf("Hello, Emscripten!\n");
- return 0;
- }
- 3. Compile the C Program
- Use Emscripten’s emcc command to compile your C program into WebAssembly (or JavaScript). Open your terminal and run:
- bash
- Αντιγραφή κώδικα
- emcc hello.c -o hello.js
- This command does the following:
- Compiles hello.c.
- Outputs hello.js and hello.wasm (if generating WebAssembly).
- 4. Use the Generated Files in HTML
- You can now use the generated JavaScript and WebAssembly files in an HTML file. Create an index.html file:
- html
- Αντιγραφή κώδικα
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Emscripten Example</title>
- <script src="hello.js"></script>
- </head>
- <body>
- <h1>Emscripten Example</h1>
- <script>
- // Wait for the module to be ready
- Module.onRuntimeInitialized = function() {
- // Call the main function from C
- Module._main();
- };
- </script>
- </body>
- </html>
- 5. Serve Your Files
- Emscripten-generated files often need to be served from a web server due to WebAssembly restrictions. You can use a simple server for testing:
- bash
- Αντιγραφή κώδικα
- # If you have Python installed
- python -m http.server
- Navigate to http://localhost:8000 in your browser to view your page.
- 6. Check Output
- Open the browser's console to see the output from your C program. You should see "Hello, Emscripten!" printed.
- Summary
- Install Emscripten.
- Write your C code.
- Compile using emcc.
- Create an HTML file to load the generated JavaScript.
- Serve the files and check the output in the browser console.
- This is a basic example to get you started. Emscripten supports many additional features, including more complex C libraries and APIs, so you can explore those as you become more comfortable!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement