Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are many VMs written in C when they look like they have C++ features?

I noticed some not so old VM languages like Lua, NekoVM, and Potion written in C.

It looked like they were reimplementing many C++ features.

Is there a benefit to writing them in C rather than C++?

like image 620
Unknown Avatar asked Nov 26 '22 22:11

Unknown


2 Answers

I know something about Lua.

  • Lua is written in pure ANSI Standard C and compiles on any ANSI platform with no errors and no warnings. Thus Lua runs on almost any platform in the world, including things like Canon PowerShot cameras. It's a lot harder to get C++ to run on weird little embedded platforms.

  • Lua is a high-performance VM, and because C cannot express method calls (which might be virtual or might not) and operator overloading, it is much easier to predict the performance of C code just by looking at the code. C++, especially with the template library, makes it a little too easy to burn resources without being aware of it. (A full implementation of Lua including not only VM but libraries fits in 145K of x86 object code. The whole language fits even in a tiny 256K cache, which you find at L2 on Intel i7 and L1 on older chips. Unless you really know what you're doing, it's much harder to write C++ that compiles to something this small.)

These are two good reasons to write a VM in C.

like image 72
Norman Ramsey Avatar answered Nov 29 '22 11:11

Norman Ramsey


It looked like they were reimplementing many C++ features.

Are you suggesting it's easier to implement polymorphism in C++ rather than C? I think you are greatly mistaken.

If you write a VM in C++, you wouldn't implement polymorphism in terms of C++'s polymorphism. You'd roll your own virtual table which maps function names to pointers, or something like that.

like image 40
hasen Avatar answered Nov 29 '22 12:11

hasen