Kernel development and C++ [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
From what I know, even though the common OS have parts written in other languages, the kernel is entirely written in C.
I want to know if it's feasible to write a Kernel in C++ and if not, what would be the drawbacks.

There are plenty of examples of well-used operating systems (or parts of them) implemented in C++ - IOKit - the device driver subsystem of MacOSX and IOS is implemented in EC++. Then there's the eCOS RTOS - where the kernel is implemented in C++, even making use of templates.
Operating systems are traditionally awash with examples of OO concepts implemented the hard way in C. In the linux device model kobject is effectively the base-class for driver and device objects, complete with DIY v-tables and some funky arrangements implemented in macros for up and down-casting.
The Windows NT kernel has an even more deeply rooted inheritance hierarchy of kernel objects. And for all of the neigh-sayers complaining about the suitability of exception handling in kernel code, exactly such a mechanism is provided.
Traditionally, the arguments against using C++ in kernel code have been:
Portability: availability of C++ compilers for all intended target platforms. This is not really an issue any more
Cost of C++ language mechanisms such as RTTI and exceptions. Clearly if they were to be used, the standard implementation isn't suitable and a kernel-specific variant needs using. This is generally the driver behind the use of EC++
Robustness of C++ APIs, and particularly the Fragile base-class problem
Undoubtedly, the use of exceptions and RAII paradigm would vastly improve kernel code quality - you only have to look at source code for BSD or linux to see the alternative - enormous amounts of error handling code implemented with gotos.

This is covered explicitly in the OSDev Wiki.
Basically, you either have to implement runtime support for certain things (like RTTI, exceptions), or refrain from using them (leaving only a subset of C++ to be used).
Other than that, C++ is the more complex language, so you need to have a bit more competent developers that won't screw it up. Linus Torvalds hating C++ being purely coincidental, of course.

To address Torvalds' concerns and others mentioned elsewhere here:
In hard-RT systems written in C++, STL/RTTI/exceptions are not used and that same principal can be applied to the much more lenient Linux kernel. Other concerns about "OOP memory model" or "polymorphism overhead" basically show programmers that never really checked what happens at the assembly level or the memory structure. C++ is as efficient, and due to optimized compilers many times more efficient than a C programmer writing lookup tables badly since he doesn't have virtual functions at hand.
In the hands of an average programmer C++ doesn't add any additional assembly code vs a C written piece of code. Having read the asm translation of most C++ constructs and mechanisms, I'd say that the compiler even has more room to optimize vs C and can create even leaner code at times. So as far as performance it's pretty easy to use C++ as efficiently as C, while still utilizing the power of OOP in C++.
So the answer is that it's not related to facts, and basically revolves around prejudice and not really knowing what code CPP creates. I personally enjoy C almost as much as C++ and I don't mind it, but there is no rational against layering an object oriented design above Linux, or in the Kernel itself, it would've done Linux a lot of good.

You can write an OS kernel in more or less any language you like.
There are a few reasons to prefer C, however.
It is a simple language! There's very little magic. You can reason about the machinecode the compiler will generate from your source code without too much difficulty.
It tends to be quite fast.
There's not much of a required runtime; there's minimal effort needed to port that to a new system.
There are lots of decent compilers available that target many many different CPU and system architectures.
By contrast, C++ is potentially a very complex language which involves an awful lot of magic being done to translate your increasingly high-level OOP code into machine code. It is harder to reason about the generated machine code, and when you need to start debugging your panicky kernel or flaky device driver the complexities of your OOP abstractions will start becoming extremely irritating... especially if you have to do it via user-unfriendly debug ports into the target system.
Incidentally, Linus is not the only OS developer to have strong opinions on systems programming languages; Theo de Raadt of OpenBSD has made a few choice quotes on the matter too.

The feasibility of writing a kernel in C++ can be easily established: it has already been done. EKA2 is the kernel of Symbian OS, which has been written in C++.
However, some restrictions to the usage of certain C++ features apply in the Symbian environment.

While there is something "honest" about (ANSI) C, there is also something "honest", in a different way, about C++.
C++'s syntactic support for abstracting objects is very worthwhile, no matter what the application space. The more tools available for misnomer mitigation, the better ... and classes are such a tool.
If some part of an existing C++ compiler does not play well with kernel-level realities, then whittle up a modified version of the compiler that does it the "right" way, and use that.
As far as programmer caliber and code quality, one can write either hideous or sublime code in either C or C++. I don't think it is right to discriminate against people who can actually code OOP well by disallowing it at the kernel level.
That said, and even as a seasoned programmer, I miss the old days of writing in assembler. I like 'em both ... C++ and ASM ... as long as I can use Emacs and source level debuggers (:-).

Revision after many years:
Looking back, I'd say the biggest problem is actually with the tons of high level features in C++, that are either hidden or outside the control of the programmer. The standard doesn't enforce any particular way of implementing things, even if most implementations follow common sanity, there are many good reasons to be 100% explicit and have full control over how things are implemented in a OS kernel.
This allows (as long as you know what you are doing) to reduce memory footprint, optimize data layout based on access patterns rather than OOP paradigms, thus improve cache-friendliness and performance, and avoid potential bugs that might come hidden in the tons of high level features of C++.
Note that even tho far more simple, even C is too unpredictable in some cases, which is one of the reasons there is also a lot of platform specific assembly in the kernel code.

Google's new-coming operating system Fuchsia is based on the kernel called Zircon, which is written mostly in C++, with some parts in assembly language[1] [2]. Plus, the rest of the OS is also written mostly in C++[3]. I think modern C++ gives programmers many reasons to use it as a general programming environment for huge codebases. It has lots of great features, and new features are added regularly. I think this is the main motive behind Google's decision. I think C++ could easily be the future of system programming.

One of the big benefits of C is it's readability. If you have a lot of code, which is more readable:
foo.do_something();
or:
my_class_do_something(&foo);
The C version is explicit about which type foo is every time foo is used. In C++ you have lots and lots of ambiguous "magic" going on behind the scenes. So readability is much worse if you are just looking at some small piece of code.

Related

Are there any downsides in using C++ for network daemons?

I've been writing a number of network daemons in different languages over the past years, and now I'm about to start a new project which requires a new custom implementation of a properitary network protocol.
The said protocol is pretty simple - some basic JSON formatted messages which are transmitted in some basic frame wrapping to have clients know that a message arrived completely and is ready to be parsed.
The daemon will need to handle a number of connections (about 200 at the same time) and do some management of them and pass messages along, like in a chat room.
In the past I've been using mostly C++ to write my daemons. Often with the Qt4 framework (the network parts, not the GUI parts!), because that's what I also used for the rest of the projects and it was simple to do and very portable. This usually worked just fine, and I didn't have much trouble.
Being a Linux administrator for a good while now, I noticed that most of the network daemons in the wild are written in plain C (of course some are written in other languages, too, but I get the feeling that > 80% of the daemons are written in plain C).
Now I wonder why that is.
Is this due to a pure historic UNIX background (like KISS) or for plain portability or reduction of bloat? What are the reasons to not use C++ or any "higher level" languages for things like daemons?
Thanks in advance!
Update 1:
For me using C++ usually is more convenient because of the fact that I have objects which have getter and setter methods and such. Plain C's "context" objects can be a real pain at some point - especially when you are used to object oriented programming.
Yes, I'm aware that C++ is a superset of C, and that C code is basically C++ you can compile any C code with a C++ compiler. But that's not the point. ;)
Update 2:
I'm aware that nowadays it might make more sense to use a high level (scripting) language like Python, node.js or similar. I did that in the past, and I know of the benefits of doing that (at least I hope I do ;) - but this question is just about C and C++.
I for one can't think of any technical reason to chose C over C++. Not one that I can't instantly think of a counterpoint for anyway.
Edit in reply to edit: I would seriously discourage you from considering, "...C code is basically C++." Although you can technically compile any C program with a C++ compiler (in as far as you don't use any feature in C that's newer than what C++ has adopted) I really try to discourage anyone from writing C like code in C++ or considering C++ as "C with objects."
In response to C being standard in Linux, only in as far as C developers keep saying it :p C++ is as much part of any standard in Linux as C is and there's a huge variety of C++ programs made on Linux. If you're writing a Linux driver, you need to be doing it in C. Beyond that...I know RMS likes to say you're more likely to find a C compiler than a C++ one but that hasn't actually been true for quite a long time now. You'll find both or neither on almost all installations.
In response to maintainability - I of course disagree.
Like I said, I can't think of one that can't instantly be refuted. Visa-versa too really.
The resistance to C++ for the development for daemon code stem from a few sources:
C++ has a reputation for being hard to avoid memory leaks. And memory leaks are a no no in any long running software. This is to a degree untrue - the problem is developers with a C background tend to use C idioms in C++, and that is very leaky. Using the available C++ features like vectors and smart pointers can produce leak free code.
As a converse, the smart pointer template classes, while they hide resource allocation and deallocation from the programmer, do a lot of it under the covers. In fact C++ generally has a lot of implicit allocation as a result of copy constructors and so on. As a result the C++ heap can become fragmented over time and daemon processes will eventually fail with an out of memory error even though there is sufficient RAM. This can be ameliorated by the use of modern heap managers that are more fragmenttation resistant, but they do this by consuming more resource up front.
while this doesn't apply to usermode daemon code, kernel mode developers avoid C++, again because of the implicit code C++ generates, and the exceptions C++ libraries use to handle errors. Most c++ compilers implement c++ exceptions in terms of hardware exceptions, and lots of kernel mode code is executed in environments where exceptions are not allowed to be thrown. Also, all the implicit code generated by c++, being implicit, cannot be wrapped in #pragma directives to guarantee its placement in pageable, or non pageable memory.
As a result, C++ is not possible for kernel development on any platform at all, and generally shunned by daemon developers too. Even if one's code is written using the proper smart memory management classes and does not leak - keeping on top of potential memory fragmentation issues makes languages where memory allocation is explicit a preferred choice.
I would recommend whichever you feel more comfortable with. If you are more comfortable with C++, your code is going to be cleaner, and run more efficiently, as you'll be more used to it, if you know what I mean.
The same applies on a larger scale to something like a Python vs Perl discussion. Whichever you are more comfortable with will probably produce better code, because you'll have experience.
I think the reason is that ANSI C is the standard programming language in Linux. It is important to follow this standard whenever people want to share their code with others etc. But it is not a requirement if you just want to write something for yourself.
You personally can use C or C++ and the result will be identical. I think you should choose C++ if you know it well and can exploit some special object oriented features of it in your code. Don't look too much to other people here, if you are good in C++ just go and write your daemon in C++. I would personally write it in C++ as well.
You're right. The reason for not using C++ is KISS, particularly if you ever intend for someone else to maintain your code down the road. Most folks that I know of learned to write daemons from existing source or reading books by Stevens. Pretty much that means your examples will be in C. C++ is just fine, I've written daemons in it myself, but I think if you expect it to be maintained and you don't know who the maintainer might be down the road it shows better foresight to write in C.
Boost makes it incredibly easy to write single threaded, or multi-threaded and highly scalable, networking daemons with the asio library.
I would recommend using C++, with a reservation on using exception handling and dynamic RTTI. These features may have run time performance cost implications and may not be supported well across platforms.
C++ is more modular and maintainable so if you can avoid these features go ahead and use it for your project.
Both C and C++ are perfectly suited for the task of writing daemons.
Besides that, nowadays, you should consider also scripting languages as Perl or Python. Performance is usually just good enough and you will be able to write applications more robust and in less time.
BTW, take a look at ACE, a framework for writting portable network applications in C++.

c++ device driver development in linux

I wanted to get more details for writing Graphics device drivers and audio device drivers using c++ for Linux box.
I am newbie at developing device drivers , Please provide me development/documentation details for the same.
Thanks
-Pravin
Coming to this page late, the question itself has been answered by Chris Stratton, but it's important to correct a couple of things Chris Becke put here that are common misconceptions with people that are not familiar with C++:
C++ does not create implicit code or data, just what you request. Even for an average C++ programmer, there will be no extra code or data. I found it out through knowing the asm behind C++, but just read Scott Meyers books it's good enough.
Not only are exceptions optional in C++, their entire code can be excluded in linkage for mostly every tool out there. This is in fact done in RT apps.
This is to address the misconceptions posted here. To add more however:
1) A novice C++ programmer may do nonsense, but a novice C programmer trying to implement by himself polymorphism and inheritance as done time and time again in the kernel just without calling it as such, will do lots more inefficient undebuggable nonsense.
2) Saying that, the only thing that may be created in base C++ is a virtual pointer IF YOU NEED IT and specify "virtual", and then also C programmers usually just create such a pointer manipulate it by themselves add lookup tables and get much harder bugs down the line due to it. As always in C++, if you don't mention "virtual" then you don't even get this pointer. Inheritance and encapsulation are of course completely free of overhead.
3) C++ creates the same amount of asm and memory as C if you don't EXPLICITLY request special features, but there is a common case when C++ is more efficient - when passing function pointers. If you use C++'s functors you can inline the pointed function. This is EXTREMELY useful in embedded apps.
4) If embedded RT uses C++ why linux doesn't? Just because of myths, so please do read this message carefully, and refer to scott meyers or better yet the asm itself. I am 20 years in RT and had the same disbelief in C++ when I switch 14 years ago, but the facts do not confirm any such distrust.
TL;DR - it's very easy to write as efficient and in a common case more efficient code in C++, studies, much industry experience and books are abound on this subject.
Linux kernel device drivers are written in C rather than C++.
Most device drivers are accessed via a special device file (/dev/yourdevice0) on which control as well as read and write operations can be performed.
User mode client programs and user mode drivers open the device file and use it as a pathway to talk to the kernel mode driver. These user mode drivers could conceivably be written in C++ or any other language.
Generally the best way to get started is to have a device which needs a driver, and learn what you need to in order to write it. And often the best way to do that is to find an existing driver for either a related device, or one with similar interface paradigms, and start by modifying that until it works for your new device instead or as well.
As there is no C++ runtime in the kernel, you will run into problems quickly. I suppose you could make a C++ runtime to run inside the kernel, but it would require some pretty good skills. Much greater skills than writing the driver in C.
Also, you would be put down instantly by Linux kernel developers. I mean REALLY put down. They'd flame you so bad, you'd never recover from it. Chances are that you would say "Screw Linux and their elitist bastards".
I don't want to sound negative, but I'm a mild and suitable voice in comparison to what you'd hear from others.
Linux drivers are developed in C. If you want to learn more about Linux drivers development, you should read this free eBook: http://lwn.net/Kernel/LDD3/
A tarball of all pdf chapters is also available: http://lwn.net/images/pdf/LDD3/ldd3_pdf.tar.bz2
C, not C++ is the language for writing (kernel mode) device drivers, and the reason ultimately is simple: C++ is an inappropriate language to use to write driver software. As a side effect of this, there is no c++ runtime available in kernel mode.
As to why c++ is inappropriate: There are at least two reasons:
Device drivers on all OS require strict code placement - some code needs to be in non pageable blocks, and non pageable memory is a limited resource. c++ generates lots of implicit code, being implicit its impossible to (a) audit, and (b) bracket with the necessary directives to guarantee placement.
exceptions have become non optional in c++. c++ exceptions are typically implemented in terms of CPU exceptions and a lot of driver code on is executed at levels where (cpu) exceptions cannot be tolerated (hence the requirement for non pageable blocks of code).
I think there are some other aspects I am forgetting, but, ideomatic c++ violates a number of constraints placed on drivers. Which is why C is preferred.
This is an old post, but I decide to write an answer since there is no answer explaining about how to do it without getting backfired.
Short Answer:
The answer is "yes, you can" … with tremendous effort. Let's just ignore Linus Trovald's opinion about C++
Long Answer:
My suggestion is writing it in C++ when you REALLY need it.
There are many pitfalls in the way of running C++ in kernel.
I recently study this subject and here’s my summarize:
There is no implementation for new and delete
It is the easiest thing to overcome.
The stack size on kernel is less than 8 kb (for 32bit) and 16kb (for 64bit).
Opps...not getting stack overrun would be challenging.
Following are not allowed
Global non-trivial variables ( there is no C++ runtime initializes it for your, using singleton would be better )
STL ( One of super powers of C++, you need to port C++ stdlib to make it working in kernel )
RTTI
Exceptions
It’s PIA to let C++ read a kernel header. If you like challenges, please at least read C++ in the Linux kernel before you go. Don't forget it has to be done every time while upgrading old code to a newer kernel.
If you’d like to know more in-depth knowledge, check out following articles.
C++ in the Linux kernel (2016)
Porting C++ code to Linux kernel (2009)
C++ article in OSDev.org
Also korisk has a demo repo in github for a barebone kernel module.
Conclusion
Again, my sincere opinion, assess the effort for running C++ in kernel module before you go.
Third time, it's better to assess the effort for running C++ in kernel module before you go!
Unfortunately, the current Linux header files are not compilable in C++ as they use new as a variable name, declare false, true and have some other issues.
You can use C++ in a Linux module but it's useless without including Linux headers. So you can't go far away from the simplest hello-world module.

Using C++ in an embedded environment

Today I got into a very interesting conversation with a coworker, of which one subject got me thinking and googling this evening. Using C++ (as opposed to C) in an embedded environment. Looking around, there seems to be some good trades for and against the features C++ provides, but others Meyers clearly support it. So, I was wondering who would be able to shed some light on this topic and what the general consensus of the community was.
C++ for embedded platforms is perfectly fine - as long as you treat it as a better C. I love the fact that the language is slightly more structured. You can still do all the things that you want to do with C. Just remember to stick to an embedded C library like Newlib or uClibc.
I particularly like the abstraction that we can build using C++, particularly for I/O devices. So, we can have a class for UART and a class for GPIO and what nots. It is cleaner than having a bunch of functions (IMHO).
The fear of C++ among embedded developers is largely a thing of the past, when C++ compilers were not as good as C compilers (optimizations and code quality wise).
This applies especially to modern platforms with 32 bit architectures.
But, C is certainly still the preferred choice for more confined environments (as is assembler for 8 bit or 4 bit targets).
So, it really boils down to the resources your target platform provides, and how much of these resources you are likely to actually require, i.e. if you can afford the 'luxury' of doing embedded development in C++ (or even Java for that matter), because you know that you'll hardly have any issues regarding memory or CPU constraints.
Nowadays, many modern embedded platforms (think gaming consoles, mobile phones, PDAs etc), have really become very capable targets, with RISC architectures, several MB of RAM, and 3D hardware acceleration.
It would be a poor decision, to program such platforms using just C or even assembler out of uninformed performance considerations, on the other hand programming a 16 bit PIC in C++ would probably also be a controversial decision.
So, it's really a matter of asking yourself how much of the power, you'll actually need and how much you can afford to sacrifice, in order to improve the development experience (high level language, faster development, less tedious/redundant tasks).
It sort of depends on the particular nature of your embedded system and which features of C++ you use. The language itself doesn't necessarily generate bulkier code than C.
For example, if memory is your tightest constraint, you can just use C++ like "C with classes" -- that is, only using direct member functions, disabling RTTI, and not having any virtual functions or templates. That will fit in pretty much the same space as the equivalent C code, since you've no type information, vtables, or redundant functions to clutter things up.
I've found that templates are the biggest thing to avoid when memory is really tight, since you get one copy of each template function for each type it's specialized on, and that can rapidly bloat code segment.
In the console video games industry (which is sort of the beefy end of the embedded world) C++ is king. Our constraints are hard limits on memory (512mb on current generation) and realtime performance. Generally virtual functions and templates are used, but not exceptions, since they bloat the stack and are too perf-costly. In fact, one major manufacturer's compiler doesn't even support exceptions at all.
In my previous company all embedded code was written in a small subset of C code due to security (SIL-2) and memory reasons. By introducing a richer language like C++ in that particular scenario would have maybe cause more trouble than benefits.
In all due respect to C++ (which is a language I really love) but I think C - in our particular scenario - was the better choice.
I bet in some cases C++ is just fine to use for embedded applications but it really depends on the application - there is a difference if your program is controlling a nuclear plant or administrating an address book on your cell phone.
I don't know about "general consensus", only the company I work for (which does a lot of development for mobile phones, car navigation systems, DPFs, etc.).
The main drawback I've encountered to using C++ on embedded platforms as opposed to C is that it isn't quite as portable - there are many more cases of compilers that don't adhere to the standard which can cause problems if you need to build your code with more than 1 compiler or outright have bugs in the implementation. Then there are environments where C++ code simply won't run - BREW's issues with relocatable code and its "native OOP" don't play so well with "regular" C++ classes and inheritance.
In the end, though, if you're only targeting 1 platform, I'd say use whatever you think is "better" (faster, less bugs, better design) for your development - in most cases the issues can be worked around quite easily.
Depends what kind of embedded development you are doing. I've done embedded development with both C++, C, and Assembly on various platforms, you can even use Java to write applications on smart phones.
For instance on a smart phone like device that's running Windows CE 5, almost all of the code is C++, including in the operating system. Only small bits are written in C or assembly.
On the other hand I've written code for an MSP430 microcontroller, which was in C, and I probably would have done that in C++ had the compiler been more reliable and standards compliant.
Also I seem to recall a university lecturer of mine talking about writing embedded code in Forth or something. So really any language can do.
Now a days it will all boil down to the C++ runtime support of the platform. You're likely to find a way to compile C++ code down to almost any embedded platform with GCC, but if you can't find a suitable C++ runtime for the platform your efforts will be futile, unless you write your own C++ runtime.
One of the few things I tend to agree with Linus is his opinion about C++ http://thread.gmane.org/gmane.comp.version-control.git/57643/focus=57918
Besides this, if you really really want to use C++ you might want to have a look at http://www.caravan.net/ec2plus/ which describes Embedded C++, or better to say you should not use in C++ for embedded systems.
The big thing keeping us with using C++ for a long time was the VxWorks support for it, which truly sucked. That supposidly has gotten better on VxWorks 6 (yes, it's been out a while... good 'ole vendor lock-in and lack of company vision has kept us stuck on VxWorks 5.5).
So for us it's mostly a question of the environment. After that, C++ can obviously be just as good as C... it's a matter of people understanding what their tool does and how to use it. C++ may make it easier to write incredibly inefficient code, but that doesn't mean we have to succomb to it.
I am currently fighting a problem with exceptions in an embedded Linux application. We are trying to port software written for a different platform that seemed to support exceptions well, but the new compiler tools (a port of gcc) reports errors when creating the eh_frame. I was against using exceptions for this tool, but the developer reassured me that modern compilers would support it well.
My opinion is that there are some advantages to C++, but I would stay away from exceptions and the standard template library. We haven't had problems using virtual functions.
C++ is suitable for microcontrollers and devices without an OS. You just have to know the architecture of the system and be conscious of time and space constrains, especially when doing mission critical programming.
With C++ you can do abstraction which often leads to an increased footprint in the code. You do not want this when programming for a resource-limited machine such as an 8-bit MCU.
Generally, avoid:
Dynamic memory allocation because it represents uncertainty in timing
Overloading
RTTI because the memory cost is large
Exceptions because of the execution speed lowering
Be cautious with virtual functions as they have a resource cost of a vtable per class and one pointer to the vtable per object. Also, use const in place of #define.
As you move up to 16 and 32-bit MCUs, with 10s or 100s of MB RAM, heavier features like the ones mentioned above may be used.
So to round up, C++ is useful for embedded systems. A main benefit is that OOP can be useful when you want to abstract aspects of the microcontroller, for example UART or state machines. But you may want to avoid certain features all of the time and some of the features some of the time, depending on the target you are programming for.

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++?
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.
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.
People are used to C. I have to admit that I'm more likely to write C for my own projects, even though I've been writing C++ since cfront 1.0.
If you want complete control over things, C is a little easier.
One obvious answer is interoperability. Any time language X has to call functions defined in language Y, you usually make sure that either X or Y is C (the language C, that is)
C++ doesn't define an ABI, so calling C++ code from another language is a bit tricky to do portably. But calling C code is almost trivial. That means that at least part of your VM is probably going to have to be written in C, and then why not be consistent and write the entire thing in C?
Another advantage of C is that it's simple. Everyone can read it, and there are plenty of programmers to help you write it. C++ is, for good and bad, much more of an experts language. You can do a lot of impressive things in C++, and it can save you a lot of work, but there are also fewer programmers who are really good at it.
It's much harder to be "good" at C++, and until one is good at it they will have a lot of bugs and problems. Now, especially when working on large projects with many people, the chance that one of them won't be good enough is much bigger, so coding the project in C is often less risky. There are also portability issues - C code is much easier to port across compilers than C++.
Lua also has many features that are very easy to implement in Lisp, so why doesn't it take that as a basis? The point is that C is little more than glorified assembler code with only a thin layer of abstraction. It is like a somewhat polished blank slate, on which you can build your higher level abstractions. C++ is such a building. Lua is a different building, and if it had to use C++ abstractions, it would have to bend its intent around the existing C++ structure. Starting from the blank slate instead gives you the freedom to build it like you want.
In many cases, code in C could be much faster than C++. For instance most of the functions in the stdio.c library are faster than iostream. scanf is faster than cin, printf is faster than cout etc.
and VMs demand high performance, so C code makes perfect sense, although the programs would most probably take longer to develop.
C++ is implemented in C. I suspect everyone was following the C++ approach.
Even though modern C++ compilers skip (or conceal) the explicit C++ to C translation as a discrete step, the C++ language has peculiarities that stem from the underlying C implementation.
Two examples.
Pointers in addition to references is entirely because of C. References are sufficient, and that's the way Java, Python and Ruby all work.
The classes are not first-class objects that exist at run-time because the class is only a way to define the attributes and method functions in the underlying C code. Class objects exist at run-time in Java, Python and Ruby, and can be manipulated.
Just a side note, you should look into CLR (Rotor-incarnation) and Java sources and you will note it is far more C++-as-C rather than modern or good C++. So it has a parallel there and it is a side-effect of abstracting for toys and making it average-performance happy for the crowd in managed languages.
It also helps avoid pitfalls of naive C++ usage. Exceptions and all other sort of things (bits David at boost consulting kicked off and more while we build sequencers and audio sampling before he even had a job :) are an issue too..
Python integration is another matter, and has a messy history in boost for example.. But for primitive data types and interfaces/interop and machine abstraction, well it is quite clear nothing beats C. No compiler issues either, and it still bootstraps many things before you get to anything as influential as it is/was/will be.
Stepanov recognised this achievement when he nailed STL, and Bjarne nailed it with templates.. Those are the three things always worth thinking about, as you don't have a decent incarnation of them in popular managed languages, not to that expressivness and power. All of that more than 20 years later, which is remarkable and all still bootstrap via C/C++.. Legacy of goodness (but I'm not defending 'dark age' C code c1982-2000, just the idea, yuo can misuse anything ).

Why would anybody use C over C++? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Although people seem to like to complain about C++, I haven't been able to find much evidence as to why you would want to choose C over C++. C doesn't seem to get nearly as much flak and if C++ has all these problems why can't you just restrict yourself to the C subset? What are your thoughts/experience?
Joel's answer is good for reasons you might have to use C, though there are a few others:
You must meet industry guidelines, which are easier to prove and test for in C
You have tools to work with C, but not C++ (think not just about the compiler, but all the support tools, coverage, analysis, etc)
Your target developers are C gurus
You're writing drivers, kernels, or other low-level code
You know the C++ compiler isn't good at optimizing the kind of code you need to write
Your app not only doesn't lend itself to be object-oriented but would be harder to write in that form
In some cases, though, you might want to use C rather than C++:
You want the performance of assembler without the trouble of coding in assembler (C++ is, in theory, capable of 'perfect' performance, but the compilers aren't as good at seeing optimizations a good C programmer will see)
The software you're writing is trivial, or nearly so - whip out the tiny C compiler, write a few lines of code, compile and you're all set - no need to open a huge editor with helpers, no need to write practically empty and useless classes, deal with namespaces, etc. You can do nearly the same thing with a C++ compiler and simply use the C subset, but the C++ compiler is slower, even for tiny programs.
You need extreme performance or small code size and know the C++ compiler will actually make it harder to accomplish due to the size and performance of the libraries.
You contend that you could just use the C subset and compile with a C++ compiler, but you'll find that if you do that you'll get slightly different results depending on the compiler.
Regardless, if you're doing that, you're using C. Is your question really "Why don't C programmers use C++ compilers?" If it is, then you either don't understand the language differences, or you don't understand the compiler theory.
I like minimalism & simplicity.
Because they already know C
Because they're building an embedded app for a platform that only has a C compiler
Because they're maintaining legacy software written in C
You're writing something on the level of an operating system, a relational database engine, or a retail 3D video game engine.
Fears of performance or bloat are not good reason to forgo C++. Every language has its potential pitfalls and trade offs - good programmers learn about these and where necessary develop coping strategies, poor programmers will fall foul and blame the language.
Interpreted Python is in many ways considered to be a "slow" language, but for non-trivial tasks a skilled Python programmer can easily produce code that executes faster than that of an inexperienced C developer.
In my industry, video games, we write high performance code in C++ by avoiding things such as RTTI, exceptions, or virtual-functions in inner loops. These can be extremely useful but have performance or bloat problems that it's desirable to avoid. If we were to go a step further and switch entirely to C we would gain little and lose the most useful constructs of C++.
The biggest practical reason for preferring C is that support is more widespread than C++. There are many platforms, particularly embedded ones, that do not even have C++ compilers.
There is also the matter of compatibility for vendors. While C has a stable and well-defined ABI (Application Binary Interface) C++ does not. The ABI in C++ is more complicated due to such things as vtables and constructurs/destructors so is implemented differently with every vendor, and even versions of a vendors toolchain.
In real-terms this means you cannot take a library generated by one compiler and link it with code or a library from another which creates a nightmare for distributed projects or middleware providers of binary libraries.
I take the other view: why use C++ instead of C?
The book The C Programming Language (aka: K&R) tells you clearly how to do everything the language can do in under 300 pages. It's a masterpiece of minimalism. No C++ book even comes close.
The obvious counterargument is that the same could be said of most, if not all, modern languages -- they also can't tell you how to do everything in only a few hundred pages. True. So why use C++ instead? Feature richness? Power? If you need something more feature rich or powerful then go with C#, Objective C, Java, or something else like that. Why burden yourself with the complexities of C++? If you need the degree of control C++ grants then I argue to use C. C can do anything and can do it well.
I choose to write in C because I enjoy working with a small, tight language. I like having access to a standard which can be read in a reasonable amount of time (for me -- I'm a very slow reader). Moreover, I use it to write software for embedded systems for which few desirable C++ compilers exist (like some PIC micro-controllers).
In addition to several other points mentioned already:
Less surprise
that is, it is much easier to see what a piece of code will do do exactly . In C++ you need to approach guru level to be able to know exactly what code the compiler generates (try a combination of templates, multiple inheritance, auto generated constructors, virtual functions and mix in a bit of namespace magic and argument dependent lookup).
In many cases this magic is nice, but for example in real-time systems it can really screw up your day.
I'm used to use C++ for my projects. Then I got a job where plain C is used (a 20 year old evolving codebase of an AV software with poor documentation...).
The 3 things I like in C are:
Nothing is implicit: you see what your program exactly does or not does. This makes debugging easier.
The lack of namespaces and overloads can be an advantage: if you want to know where a certain function is called, just grep through the source code directory and it will tell you. No other special tools needed.
I rediscovered the power of the function pointers. Basically they allow you to do all polymorphic stuff you do in C++, but they are even more flexible.
Linus' answer to your question is "Because C++ is a horrible language"
His evidence is anecdotal at best, but he has a point..
Being more of a low level language, you would prefer it to C++..C++ is C with added libraries and compiler support for extra features (both languages have features the other language doesn't, and implement things differently), but if you have the time and experience with C, you can benefit from extra added low level related powers...[Edited](because you get used to doing more work manually rather than benefit from some powers coming from the language/compiler itself)
Adding links:
Why C++ for embedded
Why are you still using C? PDF
I would google for this.. because there are plenty of commentaries on the web already
Because they're writing a plugin and C++ has no standard ABI.
Long compile times can be annoying. With C++ you can have very long compile times (which means, of course, more time for Stack Overflow!).
If you want your code to be understood by virtually any programmer write in C.
I'm surprised no one's mentioned libraries. Lots of languages can link against C libs and call C functions (including C++ with extern "C"). C++ is pretty much the only thing that can use a C++ lib (defined as 'a lib that uses features in C++ that are not in C [such as overloaded functions, virtual methods, overloaded operators, ...], and does not export everything through C compatible interfaces via extern "C"').
Because they want to use features in C99 that don't have equivalents in C++.
However, there aren't as many C99 features that are useful to C++ as people think at first glance. Variable-length arrays? C++ has std::vectors. Support for complex/imaginary numbers? C++ has a templated complex type. Type-generic math functions? C++ overloaded the standard math functions, causing the same result.
Named initializers? Not in C++, but there's a workaround:
struct My_class_params {
int i;
long j;
std::string name;
My_class_params& set_i(int ii)
{
i = ii;
return *this;
}
My_class_params& set_j(long jj)
{
j = jj;
return *this;
}
template <typename STRING>
My_class_params& set_name(STRING&& n)
{
name = std::forward<STRING>(n);
return *this;
}
My_class_params()
{
// set defaults
}
};
class My_class {
My_class_params params;
public:
My_class(const My_class_params& p) : params(p) { }
...
};
This allows you to write things like:
My_class mc(My_class_params().set_i(5).set_name("Me"));
This is pretty shallow but as a busy student I chose C because I thought C++ would take too long to learn. Many professors at my university won't accept assignments in Python and I needed to pick up something quickly.
Because for many programming tasks C is simpler, and good enough. When I'm programming lightweight utilities especially, I can feel like C++ wants me to build in an elegant supersructure for its own sake, rather than simply write the code.
OTOH, for more complex projects, the elegance provides more good solid structural rigor than would naturally flow out of my keyboard.
Most of the significant features of c++ somehow involve classes or templates. These are wonderful features except for the way the compiler transforms these into object code. Most compilers use name mangling, and the ones that don't do something at least as messy.
If your system lives on its own, as is the case with many applications, then C++ is a fine choice.
If your system needs to interact with software not neccesarily written in C++ (most frequently in assembler, or Fortran Libraries) then you are in a tight spot. To interact with those kinds of cases, you'll need to disable name mangling for those symbols. this is usually done by declaring those objects extern "C", but then they can't be templates, overloaded functions, or classes. If those are likely to be your applications API, then you'll have to wrap them with helper functions, and keep those functions in sync with the actual implementations.
And in reality, the C++ language provides a standard syntax for features that can be easily implemented in pure C.
In short, the overhead of interoperable C++ is too high for most folks to justify.
Oh my, C vs C++, a great way to start a flame war. :)
I think C is better for driver and embedded code.
C++ has some great features that C doesn't have, but many of the object oriented features of C++ can cause monumental coding messes when people write code with non-obvious side-effects that occur behinds the scenes. Crazy code can be hidden in constructors, destructors, virtual functions, ... The beauty of C code is the language does nothing non-obvious behind your back, thus you can read the code and not have to look up at every constructor and destructor and so on. A lot of the problem is bad coding practices by SOME people.
My perfect language would be a combination of C99 plus a minimal subset of safer C++ capabilities that adds ZERO (or near zero) compiler overhead to the binary output. Perfect additions would be class encapsulation and naming concepts of data and functions.
One remark about "just use the subset of C++ you want to use": the problem with this idea is that it has a cost to enforce that everybody in the project uses the same subset. My own opinion is that those costs are quite high for loosely coupled projects (e.g. open source ones), and also that C++ totally failed at being a better C, in the sense that you cannot use C++ wherever you used C.
I haven't been able to find much evidence as to why you would want to choose C over C++.
You can hardly call what I'm about to say evidence; it's just my opinion.
People like C because it fits nicely inside the mind of the prgrammer.
There are many complex rules of C++ [when do you need virtual destructors, when can you call virtual methods in a constructor, how does overloading and overriding interact, ...], and to master them all takes a lot of effort. Also, between references, operator overloading and function overloading, understanding a piece of code can require you to understand other code that may or may not be easy to find.
A different question in why organizations would prefer C over C++. I don't know that, I'm just a people ;-)
In the defense of C++, it does bring valuable features to the table; the one I value most is probably parametric('ish) polymorphism, though: operations and types that takes one or more types as arguments.
I would say that C gives you better control over optimization and efficiency than C++ and hence would be useful in situations where memory and other resources are limited and every optimization helps. It also has a smaller footprint of course.
There's also the approach some shops take of using some of C++'s features in a C-like way, but avoiding ones that are objectionable. For example, using classes and class methods and function overloading (which are usually easy for even C diehards to cope with), but not the STL, stream operators, and Boost (which are harder to learn and can have bad memory characteristics).
Because you're writing for a system where resources are tight (such as an embedded system, or some kind real bare metal code like a kernel) and you want as little overhead as possible.
There's a reason why most embedded systems don't have a C++ compiler - it's not that people don't want one, it's that cramming C++ code into that small a space is task that approaches impossible.
Until some years ago the existing C++ compilers were missing important features, or the support was poor and the supported features vary wildly among them, and so it was hard to write portable applications.
Because of the no standard naming of symbols it is difficult for other languages/applications to support C++ classes directly.
What C needed was a better preprocessor.
cfront was one and thus born c++
I'ld use C, where the 'c++ as preprocessor' would not be okay.
I'm pretty sure, at the bottom of any well written c++ library/framework/toolkit,
you would find dirty-old-c ( or static casts, which is same )