Using C++ code in Browser? It's possible!
by QUBIT_MATRIX - Saturday January 4, 2025 at 07:50 AM
#1
Yo! I didn't even know that it was possible, so here's what I found out.

First you will need emscripten:
git clone https://github.com/emscripten-core/emsdk.git cd emsdk git pull ./emsdk install latest ./emsdk activate latest source ./emsdk_env.sh

To avoid running each time source ./emsdk_env.sh just add it to your shell profile.

When you've done that, you can start coding.

Set up a new index.html file like this:
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>WebAssembly Example</title> </head> <body>     <h1>Welcome to WebAssembly Example</h1>     <p>This is a basic HTML structure for a WebAssembly project.</p>     <p id="rand"></p>     <script src="hello.js"></script> <script>   Module.onRuntimeInitialized = function() {     Module._sayHello();     var number = Module._getRandomNumber();     console.log("Random number: " + number);     document.getElementById("rand").innerHTML = "Random number: " + number;   }; </script> </body> </html>

And a hello.cpp file:
#include <string> #include <stdlib.h> #include <stdio.h> #include <emscripten.h> #include <emscripten/bind.h> #include <random> extern "C" {     void sayHello();     int getRandomNumber(); } EMSCRIPTEN_KEEPALIVE void sayHello() {     printf("Hello, WebAssembly!\n"); } EMSCRIPTEN_KEEPALIVE int getRandomNumber() {     std::random_device rd;     std::mt19937 mt(rd());     std::uniform_int_distribution<int> dist(1, 100);     int random_number = dist(mt);     printf("Random number: %d\n", random_number);     return random_number; }

Now to compile the code, you run: 
em++ hello.cpp -o hello.js -s WASM=1

After that start a http server using python: 
python -m http.server 80

Then open the website in browser: http://localhost

You can also check the developer console for output since printf(); logs to console.

Some more information - whenever you declare a function in your c++ code, you need to use EMSCRIPTEN_KEEPALIVE otherwise it would result in c++ name mangling.
Reply
#2
Thank you very much.
Reply
#3
I'll put it off, we'll figure it out after the holidays
Reply
#4
Here to remind you :3
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Fav Browser DonaldTrump 42 3,036 01-24-2026, 05:22 PM
Last Post: rosehkpiy5
  why do programmers love using anime profile pictures? kontolodon69 23 1,088 07-27-2025, 09:00 AM
Last Post: Lucifer666
  Is it possible to infect someone just by a link? Exploit0000 16 608 03-29-2025, 03:50 PM
Last Post: 0_aaron_0
  How is this possible? - Database question ST_13 12 810 03-17-2025, 07:41 AM
Last Post: termit
  What browser do yall use? raspberryroot 32 1,261 02-22-2025, 02:30 AM
Last Post: Jayze



 Users browsing this thread: 1 Guest(s)