Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compile C++ to JavaScript in a browser?

I'm aware of Emscripten and LLVM, but neither are written in JavaScript intended for a browser.

As far as I can tell, the tools exist, but they haven't been put together, but I could very well be missing some key factor that makes it very difficult to compile C++ to JavaScript in a browser.

So I'll mention my naive implementation:

  1. Compile Emscripten to C, then use Clang to compile it to LLVM, then use Emscripten to compile it to JavaScript.
  2. Compile Clang to LLVM, then compile that to JavaScript through Emscripten.
  3. Write some C++ and run it through JavaScript Clang, then run that LLVM through Emscripten to get JavaSscript
  4. Run the resulting JavaScript!

I'm sure I'm missing something from my steps. Please let me know, and let me know if there are any efforts by the community to resolve those missing pieces.


EDIT: JSCPP is the closest I've found, but it lacks a lot of features and frankly the author took on an absurd undertaking, by trying to rewrite the parser etc. on his own, rather than using existing tools. Still, close and pretty neat.

like image 894
Sophie McCarrell Avatar asked Jun 01 '17 18:06

Sophie McCarrell


People also ask

Can you run C in a browser?

Running a C program in a browser using the standard library doesn't make any sense. Even if you had the whole C library available, you wouldn't be able to use it. The browser doesn't allow interacting with the system directly from its JavaScript runtime, it's a security measure. What's the ultimate goal?

How is JavaScript compiled in browser?

In contrast, JavaScript has no compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. More modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.

Can JavaScript run C code?

js can dynamically load an external C or C++ DLL file at runtime and utilize its API to perform some operations written inside it from a JavaScript program. This is basically how a Native Addon works in Node. js.


1 Answers

It is possible to compile C++ to JavaScript using a self-hosting version of Emscripten that runs in a browser, such as emception.

Alternatively, it is possible to run a C++ compiler (or even an entire operating system) using an x86 emulator in JavaScript.

like image 114
Anderson Green Avatar answered Sep 25 '22 21:09

Anderson Green