C++ In The Linux kernel 850
An anonymous reader submits "A researcher at Reykjavik University Network Laboratory (netlab.ru.is) has just released a Linux patch allowing for complete kernel-level run-time support for C++ in the Linux kernel, including exceptions, dynamic type checking and global objects (with constructors and destructors) The implementation is based on the C++ ABI in GNU g++, but contains various kernel level optimizations, that reduces the cost of throwing exceptions by an order of magnitude, thus making C++ exceptions viable in several scenarios. Furthermore, the Linux module loader is extended to handle weak symbols in C++, so that dynamic type checking is reduced to a pointer comparison, in contrast to string comparison."
so... (Score:0, Insightful)
Re:so... (Score:2, Insightful)
Not a dang thing.
Yay! (Score:3, Insightful)
Exceptions are suddenly viable? (Score:2, Insightful)
Unlike some languages who use exceptions for events that you expect (like End-of-file) and poor programmers who think that because they're there, they must be used all the time, for everything, exceptions are a defensive programming measure to ensure that the things that should never, ever happen, are handled gracefully if they do.
Re:Sorry to break it to you... (Score:1, Insightful)
He sure as hell isn't going to start writing the kernel using Java now is he!
Re:Progress (Score:5, Insightful)
Yeah, who wants a common driver API for video, network, or sound cards...
Not to mention that drivers are all about abstracting the hardware and interface implementation from the OS itself anyway...
The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.
Yes, a kernel is more difficult than a word processor, but that doesn't mean that implementors must implement stupid C++ code. You can do some pretty neat things in C++ if you know what you are doing. If you don't know what you are doing, you can do some pretty crappy things.
Re:A good hacking exercise, but... (Score:2, Insightful)
I thought F/OSS (and Linux) was all about innovation and exploration... Sure, there are lots of things that F/OSS projects need (not the least of which is some QA effort), but it also needs folks like these people who are out doing cool stuff, even if it isn't necessary practical (or even considered practical by the 'masses' or the 'powers that be').
Re:Yay! (Score:5, Insightful)
Anyone writing a == b should notice that a & b aren't primitive types.
Re:Great news! (Score:4, Insightful)
Now if you were to start a new kernel entirely in C++, that'd be fine. The use here would be to mix the two *shudder*. No thanks. You then have a problem where the C++ people can't understand the C code, and the C people don't understand the C++ code. Its a maintenance nightmare. Just wait til the first patch that requires changing C and C++ parts. It'll be ugly.
Its much better to pick 1 language for a project and stick with it, or do a total rewrite. Mixing the two will just cause problems. Luckily, this patch has near 0 chance of being taken into the kernel.
Re:Yay! (Score:3, Insightful)
Go fork your own kernel then. Good luck.
Re:Progress (Score:5, Insightful)
That got a chuckle from me. I know what you meant, but after looking at the following (randomly chosen
if ((((u ^ v) & (v ^ w)) >> 1) & ~(u | v | w) & 1) {
if (i == 20) {
crc = buf ^ (buf >> 7) ^ (buf >> 14);
if (!((crc ^ (0x25cb9e70 >> ((crc >> 2) & 0x1c))) & 0xf)) {
data[buf >> 18] = buf >> 4;
status |= 1 > 18);
}
The simple reason for that is that otherwise the kernel would be unpredictable.
Point taken, but I hope you're open to the idea that C++ classes can be written that avoid these problems. In particular, it's relatively easy to define your own memory management scheme. This could be confusing to some (redefinition of new and delete would not be obvious in other parts of the code), but C++ has some nice features that facilitate scalability. I'm sure you'll agree that maintaining such a complicated thing as a cross-platform kernel can use some more sophisticated tools for software development than what C provides.
Re:Progress (Score:2, Insightful)
C++ in the kernel? (Score:4, Insightful)
The value of an OO language in larger projects is enormous. Basically there are simply too many things that could go wrong at any point, and the overhead associated with C++ (memory use, exception setup, excess copying, dynamic checking) is a small price to pay for the additional benefits it provides. As you get closer to the metal though, and you have to watch what you are doing more closely. You want to know exactly when memory is being allocated, when something may go wrong, and only want to set up to catch exceptional circumstances if you know they may occur. Resources in kernel-land are expensive. C allows this kind of control, C++ does not.
My former boss would love to see me defending C over C++ like this. The irony.
Having said that, the capability to run C++ code in the kernel would certainly be nice, provided it didn't impact the existing code. I'm not sure how this one could be pulled off though. There'd be too much code that would need to be made aware of exceptions, destructors, so forth.
That's not what exceptions are for... (Score:5, Insightful)
Sorry, but I think you're missing the point of exceptions. They are supposed to decouple generating the error from reacting to it, because in practice that's often useful.
Exceptions are a systematic way to return control multiple layers up the code, without cluttering the code in between passing information it doesn't need to know or care about. They are best used where the code that directly causes the error can't handle it because it doesn't know how, and the code that handles it doesn't care where it came from, because the code that was trying to run aborted anyway.
You could write at least a good length article on what exceptions are and aren't good for, but in short, if you ever throw exceptions exclusively at one level and catch them exclusively at the next level up, there's a good chance you're using the wrong tool for the wrong job.
Re:Yay! (Score:4, Insightful)
Only if you've overloaded operator==. But in that case, this is just a function call. A function call in C could just as easily add a few KB. The only difference between the languages here is that C++ gives you the "syntactic sugar" option of creating functions with the same names as operators. You can choose not to do that if you perfer and just use a regular function name, as in C. In no way does the ability to create a function named "==" instead of "Equals" show any more "lack of control" over code size than in C (exceptions might have been a better example).
Re:Exceptions are suddenly viable? (Score:4, Insightful)
You can senselessly dump all your error handling code in the middle of nowhere using return-value error codes, too, if you really want to.
C vs C++ (Score:4, Insightful)
Personally, I think mixing C++ into the kernel is not a good idea, generally, in my experience certain aspects of C++ are messy to debug, and if you're gonna skip using them, then perhaps you should've stuck to C.
Also these guys used to distribute their pronto project in one tarball, a modified version of the Linux kernel, and the website for downloading it made you have to accept *their* license. When the issue of whether this was possibly in violation of the GPL, and if they should rather distribute a clean patch, came up on the local GLUG mailing list (www.rglug.org) their response was rather shocking, they absolutely refused to acknowledge that they should perhaps distribute their code in another way, and even reverted to speculations about the legitimacy and enforcability of the GPL. To their defense, the original 'article' on the matter was very inflammatory and made some rather derogatory remarks, and IIRC they changed their website some time later.
Multicasting is a cool technology, and dynamic multicasting routers such as RU is researching and developing with the Pronto project, may well be the key to using the internet as a single infrastructure for 95% of our content-delivery and communication needs (digital TV through the internet, without exponentially increasing bandwidth load, etc), so I hope RU keep on, and their work be fruitful
Also, to everyone who refers to the creator of Linux, as 'Linux'... his name is 'Linus', get it through your heads, this is slashdot.org not mouthbreathers.org
Re:More Confusion (Score:3, Insightful)
Note: if you use ALL the techniques of C++ in your programs at the same time, then you are not a good programmer, period.
less snarky (Score:2, Insightful)
C++ is not distinct from C because it's evolution has been driven by adhering to the systems oriented philosophy of C and also by a very real effort to keep C++ "compatible" with C.
Obviously, to take advantage of C++'s improvments, you have to learn and use them.
Re:Who cares? (Score:5, Insightful)
Please people, I know Linus is God, and I have a lot of respect for the man. But I don't care who it is, if people make statements like this, I'd like to see some back up.
It sucks. Trust me - writing kernel code in C++ is a BLOODY STUPID IDEA.
When someone says 'trust me' it either means "I'm too lazy to explain" or "I haven't really got something to prove it".
The fact is, C++ compilers are not trustworthy. They were even worse in 1992, but some fundamental facts haven't changed:
Well, I don't want to start a flamewar here, but while this may be true for the GNU compiler, it certainly is NOT true for, for example, the Microsoft compiler. (I know, how dare I say that...) It has produced code from C++ source for a _very_ long time and even the optimizer works very well.
* the whole C++ exception handling thing is fundamentally broken.
Why?
It's _especially_ broken for kernels.
Why? Maybe for the Linux kernel, because it wasn't designed with C++ exceptions in mind. And I'm not even say that that's bad, but why is it in gerenal broken for kernels?
* any compiler or language that likes to hide things like memory allocations behind your back just isn't a good choice for a kernel.
Well, that's really implementation and as such is your choice, it's not the language. Furthermore, no-one forces you to use _all_ possible language features. I personally stay away from many C++ language features such as overloaded operators.
* you can write object-oriented code (useful for filesystems etc) in C, _without_ the crap that is C++.
But why would you if you can do it cleaner in C++ and have the compiler generate the same quality code? What is crap about C++?
What Linus needs to do is go back to the old days where he looked at assembly output. I still do that and have compared C++ with C many times and I can't see why anyone would not use C++.
You don't have to use all the bells and whistles, shit, you can write plain ANSI-C and still use a C++ compiler for it's superior type checking etc.
Anyways, to each his own, I guess...
Re:Exceptions are suddenly viable? (Score:1, Insightful)
Just because you don't understand the value of something doesn't make it valueless...
Re:Alright!! (Score:5, Insightful)
All you need is policy that covers use of various features, just like the Linux kernel requires policy on use of C.
multiple platform support becomes template specialisation, locking rules can actually be enforced by the language (ie, to get member functions to access an object, you can require that you call a member function to return a mutex object which has the members, and when that mutex is destroyed naturally, the lock is freed. fast, safe, secure.
The question is how customisable is the compiler for how virtual functions, etc, are implemented. Those are the only issues to be concerned about because C++ is plain better than C.
Re:Who cares? (Score:5, Insightful)
Don't like exceptions? Don't use them. C++ doesn't require you to. Personally, I don't use them unless I have to interface with other code that does. I usually compile with exception support off.
Is allocating memory in a constructor likely to cause problems? Make it a standard code practice for your project to never cause non-explicit memory allocation. Destructors can be forced to run at a specific time with delete or by using forced scopes (use {} around the lifetime of the local var). Copying objects in a standard way is easy to do, espescially if you always pass classes (structs) as references or by pointer. Are you saying that C++ always uses more memory than C? That's silly. If you can't call memory allocation functions right now, then allocate things on the stack. Make sure that the objects you create and the functions you call don't alloc either. You would have to make sure the functions were safe in C too. Ok, so don't use the heap. There is no reason that C++ needs to use the heap; everything can be allocated on the stack. Just like C. Assembly isn't too nice if you care about portability. It also depends on the architecture about how nice and simple it is. Segmented memory in assembly can be a nightmare.
Don't use the STL implementation of linked lists if you don't like it. Done properly, you could use templates for even more than that, like different index sizes for a filesystem; a 32 bit version for small volumes, a 64 for large volumes and a 128 for extremely large volumes. Since there is no primitive 128 bit type, C++ lets you override operators to create a new type that acts exactly like a primitive. This word size would be a template parameter of the filesystem class; a static version created for 32, 48, 64 and 128 bit or whatever. One code set, no redundancy. Remember the Sun story about a 128 bit filesystem? It could be as easy as recompilation!
How about namespaces? These would be very useful in the kernel, IMHO.
Member functions are nice for associating a function with an object.
Private data members allow you to put data in a structure that outside code doesn't need to know about so you can change it later without breaking compatibility. Documentation can do it too, but this can enforce it.
I bet there could be some good uses for smart pointers.
The fact that a language has a feature does not obligate you to use it. You can use code standards in your project that set sane regulations for the code in the project. You need standards for any a sizable project in ANY language, including C. I'm sure that the Linux kernel already has rules as to naming conventions, header file control etc... More could be created to regulate good usage of C++ in a kernel environment.
Re:nice (Score:4, Insightful)
The core of Windows in C++? Maybe I am wrong, but If my memory serves me well, it was C and asm.
Re:Progress (Score:5, Insightful)
Complex code becomes predictable by building layered abstractions with well-defined interfaces. C++ supports that better than C.
Let's say the error logging function used the string class (which likes to allocate memory behind your back).
The kernel almost certainly wouldn't be using "the" string class, but its own string class, adapted specifically to the needs of the kernel. Right now, the C-based kernel doesn't use the user mode C library either, after all.
If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash.
Quite to the contrary. Not only would the kernel not crash, with a properly designed string class, out of memory conditions would actually be guaranteed to be handled correctly in all string operations everywhere in the kernel. No more case-by-case checking and handling of whether the memory allocation happened to succeed this time or not. In this particular case, the string class would throw an out-of-memory exception in the error handler and the stack would unwind up to the point where there is a handler.
Furthermore, the error logging function can decide to intercept such exceptions and print an emergency error message on the console, and it can do so reliably without ever having to worry about checking a single status or return value.
Altogether, this is a big improvement over C-based handling of such situations. But if you want to keep this situation from occurring in the first place, there is no more reason for the error logging function to allocate memory in C++ than there is for it to do so in C.
C++ in embedded applications is a bad idea (Score:4, Insightful)
Embedded dev is now often C++ based.
Too bad too. I am developing FAA Level A avionics software using C++, I am sorry to say. What a debocle. For starters, the compilers for non-gcc supported platforms uniformly suck. Typical compilers for DSP's lag the C++ standard by 10 years, and crash frequently. And my project is proof that if a language feature exists it will be used, no matter how pointless. For example:
or
Gross. Please keep C++ out of the Linux kernel!
Re:Who cares? (Score:3, Insightful)
Read Meyer's "Effective C++" and "More Effective C++". There's a lot of hidden object creation that goes on. These take memory. If they malloc memory in constructors, they use LOTS of memory.
Ok, syntactic sugar, but not a bad one. Of course, you could just have a naming convention, and you would likely get as much compliance there as you will with namespaces.
We have that. Function pointers. Kernel uses them all over.
Static data variables do the same thing for single instance. For multi instance hold a pointer to a block of data, hold it in an integer, and call it a handle. Don't let the other guy see the implementation of the block.
The problem goes back to the top- you're hoping that you can get hundreds of developers with no central control to follow a bunch of rules. They won't. They don't on propriatary projects when they're being paid to do so. On an open source project, it'll be worse. Its easier just not to use C++ than to say "Use C++ but not features x,y, and z".
Re:Progress (Score:3, Insightful)
It's not so much that C++ itself is so bloated etc. but that some of the common C++ programming idioms - full of templates, overloading, deeply nested class hierarchies with virtual methods, etc. - can lead to bloat. It's never good to have what looks like a simple assignment statement turn into thousands or even tens of thousands of instructions, but it's particularly dangerous in the kernel. Templates are particularly bad because they get re-instantiated for every type they're used with and that can very rapidly cause executable sizes to balloon out of control. They're a non-solution to a problem that's more than adequately solved by treating types as first-class objects, or by lower-level methods such as explicit dispatch-table pointers.
Sure, you can tell your developers to use a subset of C++ that doesn't have such problems, but what's the point? Why pay the runtime-support and tools cost and require greater vigilance in code reviews just for some syntactic sugar (which is all that would be left)? I'm not absolutely opposed to using C++ in a kernel where it's already supported, but there are costs that would have to be justified compared to just using C.
C++ is a bad idea for bad programmers (Score:5, Insightful)
> Register_set regset(base_address);
> regset.write(SOMEREG_OFFSET , Register_set::BIT_A | Register_set::BIT_B);
Only a complete novice would write code like this. Your code setting *SOMEREG_ptr = BIT_A | BIT_B will work just fine in C++ too. In fact, you could transparently support multiple types of registers by overloading operator= of SOMEREG_ptr, which could be a polymorphic class. And if you think that is going to bloat your code, you obviously have never looked at the output of a good compiler like gcc. A good C++ design is FAR more readable than any C hack you can come up with.
> Typical compilers for DSP's lag the C++ standard by 10 years
That is the problem of your compiler, not the language. Stop bashing C++ when you should be blaming your vendor for not being able to write a decent compiler, or even port gcc to their platform.
Re:Yay! (Score:1, Insightful)
And it can do the same in plain ANSI C, for example when "a" is defined as a macro.
If you say one should be careful what features of C++ he uses and not to use this and that, I say one should learn proper C skills instead.
Maybe you should just use proper C++ skills; it's not that hard, and in the end, it results in better code.
Re:Exceptions are suddenly viable? (Score:4, Insightful)
The whole point of exceptions is that you don't care. If you care about each specific read, you wrap each read in it's own block (the same as error conditions, except that you'd use an if block).
Whats the state of all your objects?
This is why object-oriented C++ is so wonderful and Java is so bad - your objects are automagically in the correct state because you allocate and clean up resources in thier destructors. If an object is in scope, it's in a clean state. If it's not in scope, it's not. You can write some really concise, clean, reliable code using this concept - it's where the true power of objects comes into play. In C, you have to manually check EVERY call and clean up EVERY resource - it's very susceptible to programmer error, especially in deeply nested call chains with gotos and whatnot all over the place (like the Linux kernel, for example). In Java, which doesn't have destructors, it's even worse because you've got exceptions with no automatic cleanup, which means you've got to have all sorts of ugly nested try/catch/finally and state management.
Exceptions are a nice way of dealing with problems, especially nested calls. But combined with destructors, they're a magnificent way of keeping error handling safe.
People use goto in C because they want a nice exit point in the case of failure. People use exceptions for exactly the same reason - it simplifies error handling. It's true that it's physically seperate from the code, but on the other hand it's within the same block so you've got a visual/indendation indication at least. If you think exceptions are a maintainers nightmare, then you've never tried to fix an error in a function with 40 different exit points, with almost identical cleanup code at every point. A C programmer would use a goto so that there's not so much duplicate code and it's easier to maintain. A C++ programmer would use exceptions and automatic objects to do exactly the same thing, in roughly the same lines of code, with with even less (quite possible 0) duplicate code and greater modularity.
Re:More Confusion (Score:3, Insightful)
If your company refuses to hire people who refer to C/C++, then your company must not know what C++ is. If it did, it would a) Know that C++ is essentially a superset of C and therefore it is intelligent to make statements that apply to the dual entity referred to generally as "C/C++"; and b) You would have some kind of concept of class inclusion, and be able to understand that C and C++ are part of the same 'language family' -- it is therefore just as allowable to talk about C/C++ as it is to talk about 'Germanic' or 'Slavic' or 'Romance' or even 'Indo-European'.
Such an overgeneralizing, bigoted, and asenine criterion is beyond all stupidity.
Re:Dumb Person... (Score:5, Insightful)
Essentially, C++ offers support for many, many different types of programming. Just like there are some tasks for which object-orientation is better than procedural, there are some projects for which generics are superior, for which functional programming is superior, etc., etc.
C++ is not an object-oriented language and was never intended to be (as reading Stroustrup will tell you); C++ was meant to support a broad variety of programming styles, of which object-oriented programming is just one.
So what do we gain by allowing the kernel to use C++? Mostly, we allow kernel programmers flexibility to solve problems in different ways. However, the trick to this is that while we're giving the programmers additional tools with which to do their jobs, we're giving them more complex tools which sometimes fail in extremely bad ways.
Exceptions are a good example. Up until very recently, code that used exceptions was about 5% slower than code that was exception-free. This five percent penalty was unavoidable overhead. Now, some people got bit by this five percent hit (usually people working in realtime fields) and came to the conclusion of "oh, C++ sucks for RTOS because exceptions give a five percent hit".
The reason why they came to that conclusion is easy to understand: it's easier to blame their tool than their knowledge of the tool. It's easy to say "oh, C++ sucks"; it's harder on the ego to say "well, I didn't know that about C++, and it bit me in the ass."
Many--and maybe most--people who condemn C++ have not used it recently. Linus, for instance, condemns C++ based on his experiences with it from 1992, six years before the C++ language had been standardized and ten years before GNU got a decent C++ compiler.
C++ is a very complex language, as anyone, even C++ aficionados, will tell you. On the other hand, in the hands of someone who's made the (significant) investment to become a skilled C++ programmer, C++ is capable of breathtaking power and elegance.
The conflict is essentially this: one side believes "if we add C++ support to the kernel, we'll have lots of incompetent C++ people doing all manner of incompetent C++ things which are really stupid and killing performance" and the other believes "with C++ support to the kernel, we give programmers different ways to solve approach problems, and I'm not going to deny all programmers the benefit of C++ just because many programmers can't use it effectively."
I sincerely think that adding C++ support to the kernel is a good idea, subject to some strict requirements. For instance, have a C++ Czar for the kernel, someone Linus trusts to have wisdom and understanding of C++; and make sure that all C++ checkins to the kernel go through the C++ Czar to ensure that C++ is being used wisely, and not as an impediment to understanding.
The kernel is too bloated as it is... (Score:3, Insightful)
Ged rid of all these crappy drivers and related crap out of the kernel source tree, and just provide the basics. They should start a new sister project for maintaining drivers, and split them up too for goodness sake. Why should I have to diff the whole stinking tree, if i've made a few changes to a networking components? or added a soundcard driver?
BEOS was onto a good thing using the microkernel, completely seperate subsections for drivers, and the ability to control teams of processes - these would all be very useful in a mainstream O/S.
C++ output may be a bit larger, but isn't all that bad, objects are very easy to visualise, and the source usually ends up smaller. Kernel Modules with a better designed interface would be an good start. And if C++ could help out here, why not?
It's about time the kernel guys opened up to a some fresh ideas. Sure, linux is already an awesome O/S, but you can't fight an the evil dragon wearing nothing but asbestos undies...
As long as they keep STL out of the kernel I will be happy. (imho templates make code look butt ugly and a behemoth to maintain)
What about BeOS? (Score:3, Insightful)
Re:Who cares? (Score:3, Insightful)
Temporary objects. Compilers create temporary objects, especiall arounjd function calls/returns. These call the constructor, which may call malloc. The number of situations temporary objects can be made is actually failry high and very complex. If the language is creating objects you don't explicitly ask for and calling malloc off that, I count that as the language using memory. Its the fault of the language for creating the object.
Re:Exceptions are suddenly viable? (Score:5, Insightful)
Exceptions in the kernel are inherently a bad idea. An uncaught exception is a kernel panic. By contrast, an unknown error return is still an error, and usually the right thing happens. The risk of allowing exceptions in the kernel far outweighs any possible benefit. That's why nearly every kernel that has ever used C++ at any level has explicitly excluded exceptions. (That and the very nature of exceptions inherently results in worse performance than using error returns. In the kernel, performance is far more important than facilitating programmer laziness. :-)
It would be wise for the Linux community to learn from other OSes that have tried to do kernel exceptions. Even the Windows kernel developers rejected them as a bad idea. Don't do it. Don't accept any patch that allows it.
Re:Who cares? (Score:3, Insightful)
This, of course, the wrong end of the proverbial stick. The benefit of C++ is that it lets you do pretty much what the kernel does now, only in a way that's easier to understand and more maintainable.
To get any substantial benefit for existing code, you'd need to translate the entire kernel into idiomatic C++, which is a huge task. For new code, OTOH, C++ compatability should be a win. Unfortunately, the only way to prove this is to a) support C++, b) implement the new code twice, once in C++ and once in C, and c) compare them.
Given that almost nobody is willing to implement their new feature twice just to prove a point...
Re:Exceptions are suddenly viable? (Score:3, Insightful)
I ended up having to rewrite the com_error object so it traced out a message with the location of the actual error... much later on I worked out how to stop it being thrown in the first place & to return the documented error codes.
That's the real problem with them - unless you have a catch() after nearly every statement it's basically impossible to work out what went wrong - 'File Not Found' - which file? which function? Why, exactly?
I totally disagree that you mostly don't care where the error was thrown. I *do* care, because I have to fix it. Maybe the end user doesn't care, but even then I want the code to generate an error report that tells me where to look.
Re:Who cares? (Score:2, Insightful)
Sorry, that argument doesn't quite work for me.
As I understand it, this patch would simply add runtime support to give a kernel-module-writer the option of experimenting with C++, if desired. Accepting it would not force anyone to use C++. It possibly that the patch itself could be written in C, not C++, so accepting it (or a similar patch) need not introduce C++ into the kernel.
Once that support is there, you could leave it for a few years while experimenting. No one is forced to rewrite any code (unless they want to). In the meanwhile the kernel becomes increasing modular and, one day, one of the core subsystem might choose to use C++. For example, the VM subsystem could choose to use C++ without having any visible impact on other subsystems.
Linux moves forward through evolution, not revolution. Add the support, and see if its useful. If it is, people will eventually use it as the old maintainers drift away.
Re:Progress (Score:2, Insightful)
I don't understand why a common driver API is not possible to do in C... Would you care explaining?
I didn't mention anything about choice of language. The OP didn't either.
Not to mention that drivers are all about abstracting the hardware and interface implementation from the OS itself anyway...
Does that mean we should give up on transparency?
No, but I fail to see why the kernel would have to see into the details of how a device driver is implemented. As long as it conforms to a well defined interface, it shouldn't care at all how it is implemented.
You can do some pretty neat things in C++ if you know what you are doing. If you don't know what you are doing, you can do some pretty crappy things.
This (again) begs the question: what can you do in C++ that you can not do in C? Is it just because classes, objects, constructors, destructors, inheritance, and all that crappy OOP stuff is specificly declared that C++ is that superior? You can do pretty well the same in C! There is absolutely no consistent technical reason supporting the use of C++ in the Linux kernel!
Quoting the FAQ [kernel.org] that you should indeed read since there are some Linus quotes there:
I agree with that quote but it has nothing to do with the fact that Linus said it. (And it doesn't "beg the question" because that phrase means something else.)
I've written OO code in C for the past 17 years or so as well as programmed in C++, Java, and C# (more recently) among other lesser known languages. I'm fully aware that I can do in C what C++ does, it just may take a bit more coding on my part to do some of the things. In fact, early C++ compilers were just manglers that output mangled C and compiled that for your program. With newer C++ standards, it isn't that easy anymore, though. Anyway, just as it was said in the quote that you posted, it isn't important what language you use, so what's with the beef against C++?
C's reason for existence; BSD versus Linux (Score:3, Insightful)
Re:Exceptions are suddenly viable? (Score:4, Insightful)
> Obviously an unsuccessful operation.
Well, you want to communicate back to the higher level code *why* the call failed.
Oh, wait, no problem!
Well set a global variable called errno.
Oh yes, and scratch our heads for a seeming eternity while we figure out exactly how to virtualize different errnos for each thread.
And hope to hell that no failing system calls get called between when we failed and when the user checks errno.
Rock on!
Re:Alright!! (Score:4, Insightful)
Any language only goes so far, the thing that determines whether a software development project succeeds or not is policy and attitude.
For example, you can prevent changes in the apparent behaviour of the language by prohibiting operator overloading, template specialisation, and implicit constructors. Oh yeah, banning macros, which you also have the problem with in C.
And you don't have to worry about unexpected exceptions, because even if you didn't try-catch, the compiler cleans up *all* your objects in *every* case and tells the function that called you that you failed, and "here's why". The only reason you need to know about exceptions being thrown is to clean up resources and data-structures - and that is done in the destructors for auto class variables, so no problem there.
Re:More Confusion (Score:2, Insightful)
Re:More Confusion (Score:5, Insightful)
No, C solves problems differently.
Re:More Confusion (Score:5, Insightful)
It's just discipline (Score:3, Insightful)
Nobody's forcing you to use C++ features where they would be a bad idea.
Re:Exceptions are suddenly viable? (Score:3, Insightful)
An uncaught exception results in a call to unexpected(), which by default calls std::terminate(). This behavior can be overridden using std::set_unexpected() to, for example, return an unknown error to the caller of the currently executing system call.
Re:Yay! (Score:5, Insightful)
Unless I misunderstood when I RTFA, that is exactly what the authors intend to do. And I, too, would like to wish them "Good luck." Linus obviously believes that C++ in the kernel is undesirable, but we'll never find out for sure until somebody like these people have the guts to actually try it, and the persistence to maintain a current patchset (or fork) long enough for the idea to catch on.
Not Likely (Score:1, Insightful)
Re:Progress (Score:3, Insightful)
Except that they can't be overloaded in that case as both operands are built-in types. You can't overload an operator unless at least one of the two operands is a user-defined type, which prevents people from making this do something unexpected. That is, you can't make operator^(int, int) play the star spangled banner, no matter how hard you try.
Re:Yeah, it's not, until someone finds out (Score:1, Insightful)
Re:Alright!! (Score:2, Insightful)
Macros in C are used for readability and easily debugged. All you have to do is grep for the #define.
The locking order in C code? THERE IS NO LOCKING ORDER. You have to explicitly mange these aspects in C and anyone can immediately determine it from looking at the code.
Your explanation of memory management within the kernel is at best naive. What if the code is called within a context that is higher (or the same) IRQ level as the VM pager? There is no heap! There is only a small amount of non-paged memory that had to allocated ahead of time and the very limited kernel stack.
And your notion of what an exception is (in both user mode and kernel mode) is beyond naive. Exceptions can happen for any number of reasons. Simply catching them and cleaning up may not be sufficient. Maintaining an understood state for the rest of the system is the proper course of action. In a network application it may require invalidating a cache to avoid data corruption, or in a kernel routine setting up an I/O request to be handled at a lower IRQ level. Do you propose having all this in the destructor?
Sure you can randomly clean up everything you can think of, return to the caller, and hope everything works, but in the kernel an unknown exception results in an inevitable reboot. And on a clustered network -- data loss.
Re:C++ is a bad idea for bad programmers (Score:3, Insightful)
The code sample was meant to show that some people will find excuses to use C++ features when the C equivalent works perfectly well. *HOPEFULLY* this won't happen in linux.
amightywind wasn't bashing C++ in general, only in the context of embedded dev. I think they made this perfectly clear in the first 2 lines.
I'd say they do blame the vendor, but the current state is that C++ in not good for embedded dev. If you can't get a good C++ compiler for the platform, then C++ is not a good choice of language. This has no direct reflection on C++ as a language.
Re:More Confusion (Score:1, Insightful)
No, it's the first step to hating C++. I was taught "C++" as a "better C", and nothing made sense. It was like mixing chocolate cake and ketchup. Both may be good, as long as they are kept separate.
After that experience, I went to pure C, and found out that C is really a nice language.
Later, I have learnt a few things about C++, real C++ this time, not "a better C" - and I started to see that if used right, C++ is a nice language too. As long as you DON'T use it as "a better C".
Re:Exceptional programming (Score:2, Insightful)
But then I realised it's Baldrson [geocities.com], and the penny dropped. Most trolls are indistinguishable from idiots, but Baldrson is a genius who's indistinguishable from a troll. I think he comes from a parallel universe where his beard [geocities.com] is considered normal.
Someone needs to get Baldrson and ESR [ibiblio.org] alone in a room together. I'm intrigued to know whether they'd fight or make out. But what if the combined comedy facial hair [wikipedia.org] reached critical mass? Is it worth the risk?
Re:Alright!! (Score:4, Insightful)
That's wrong, too. There is no way you can change the meaning of e.g. int i=3+4; in C++. Of course there are things where you can change the meaning, but that's no different to the following statement about C: "every function call might be changed from what the author has intended (and tested) when somebody changed the definitions of what that function calls."
Clearly if anything you inherit from changes semantics, then this is a break of interface, just as changing semantics of a function is a break of interface. You shouldn't be surprised that if you use a library which does not conform to the specification your program expects then your program breaks. That's independent from language, coding style, programming paradigm, it's even independent from programming (e.g. if you think "moron" is something positive, then telling someone a moron will surely not have the effect you expected).
Re:More Confusion (Score:5, Insightful)
"Exception Handling"
setjmp(), longjmp()
"Function Overloading"
Function pointers
"Operator overloading"
Ok , you can't do this in C.
"New/Delete"
Its easy to create simple malloc()/free() wrapper functions.
"Inline Comments"
Eh? Whats stopping you doing
"References"
These are hardly a selling point of C++ in my opinion. Implicit pass by address symantics should NEVER have been put in a modern language. Besides , after compilation they produce the same code as that using pointers.
"Others I'm sure"
Inheritance, templates etc. It just depends on how much you way syntatic clarity (C) against functional clarity (C++). Personally I think anyone who sticks religiously to either C or C++ without every using the other probably isn't a very competant programmer.
Re:Progress (Score:3, Insightful)
Obviously, C does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.
The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the printf function (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.
I hope you get the point.
You obviously have little real world experience (Score:3, Insightful)
Thats an assanine statement to make. I've been a professional programmer for 11 years, most of that doing C AND C++. Yes thats using both languages or a mixture of the 2 depending on what project I've worked on. And I'm quite happy doing either high level OO template programming (C++) or low level boolean bit operations, memory management, function pointers etc (C). Most people I know who do C/C++ would have the same ability and most people I've interviewed myself I would expect the same off. If they can't handle malloc & free they're as useless to me as if they can't handle temaplates.
"in my head I know that the interview is probably already over."
Then I suspect you're probably responsible for your company not hiring a lot of good people since you obviously have an arrogant attitude and give the impression that only you can be master of both. If you worked for me I'd never let you near an interview room.
Re:Who cares? (Score:3, Insightful)
Except that in C++, you'd write:
and not have any problems at all.
Re:Who cares? (Score:2, Insightful)
If you don't think thats a problem- try putting a cout statement in a constructor, and write a function that takes an object as a parameter and returns that object.
Although I agree that c++ isn't a good choice for a kernel, here i've to say that you can in fact produce good code simply remembering to pass args to a function as constant references. You've a good control over when and why temporary objects are created, if you fully understand what your code does. More, modern compilers like g++ use optimizations to avoid creating non-wanted temp objects (like in "C* obj = new C(C(otherobj));") and thus eliding redundant constructors (that was a silly example, but there's plenty of situations).
I believe that for a good c++ programmer memory management is simplier and cleaner than c's one, instead of loose and chaotic. This doesn't mean that malloc() sucks; it just means that new/delete aren't evil and help you if you know how to use them.
Assembly gets a bad rap, really its a nice simple language.
Simple doesn't mean portable.
The gain of c++ over c is really substantial, BUT I don't think that c++ is a good choice for kernel development, mainly because it's too "tempting" to add millions of useless features. c is neat, easy and has a really small grammar: it's something you can learn in a week. c lets you to act to a more lower level, is faster to compile, and extremely portable (that's the main reason why Linus won't like c++). I believe that c lets programmers to concentrate more on the real algorithmic problems of the code (such as sorting, scheduling, threading...) than on inheritance/class (syntactic) related ones.
Re:More Confusion (Score:2, Insightful)
However, the C++ way generally is more convenient, and I would go so far as to say that convenience, in the right measure, makes for better code. Rather than inventing your own wrappers for freeing memory, for instance, with "delete" all of that gets put into a destructor which can be easily found in any class that implements one.
Obviously you can go overboard on syntax, but clearly if something becomes fundamental to the language, then there's a strong argument for adding syntax to support it, if only to prevent people from reinventing the wheel.
Re:More Confusion (Score:4, Insightful)
"References"
These are hardly a selling point of C++ in my opinion. Implicit pass by address symantics should NEVER have been put in a modern language.
Are you joking? References are the ultimate syntactic way to say "don't mess with the pointer, just use the object". The fact that you can't do arithmetic on references, or delete references, or assign references, without casting them in various ways is exactly the kind of friendly reminder that helps prevent a large class of common pointer-related programmer errors.
Besides, after compilation they produce the same code as that using pointers.
So does asm.
Anyhow, C has got issues. C++ added constructs to automate many aspects of modern programming, the point being to help reduce bugs by giving friendly syntactical shortcuts and reminders, and writing some of the code for you. It's not an issue of what can and cannot be done; it's more of a likelihood of programmer error thing. C++ has issues too, mostly because of various odd syntactic decisions that were made, several of which stem from trying to make it backwards-compatible. Some of it is plain ugly :) But it sure as heck puts bread on my table without stressing my brain too much.
Now I find myself evaluating the new Java, and C#, which both add even more features and little reminders to programmers to avoid common programmer errors. D is not looking too shabby, though it doesn't have anything like the market strength of either new Java or C#. Personally I think they are all getting bloated, adding too many keywords and not simplifying and unifying things enough. Back in my university days me and a buddy started designing a language we called D-, but we stopped after we realized how much time it would take to actually make it happen. I still dabble with the design on my spare cycles. Maybe some day... just maybe...
Re:You have no idea what OO is all about. (Score:2, Insightful)
There's more to OO than mere polymorphism. Encapsulation is a very useful feature in its own right. By 'could cause problems', read 'could cause problems in kernel development'. For example, virtual functions require lookups and dereferencing at runtime, and the vtable arbitrarily increases the size of an object, both of which are undesirable in kernel development.