Home > Linux > C++ in the Linux kernel?C++ in the Linux kernel? Submitted by Lumbergh 2004-10-28 Linux 45 CommentsThis company has a patch that allows C++ in the Linux kernel, but Linus thinks otherwise.About The Author Eugenia LoliEx-programmer, ex-editor in chief at OSNews.com, now a visual artist/filmmaker.Follow me on Twitter @EugeniaLoli 45 Comments 2004-10-28 8:39 pm there is no point, if anything it would make things harder. usually people realize this _after_ doing all the work. think before you act next time. 2004-10-28 8:45 pm hum I am not a kernel developer but saying after 12 years that c++ compiler are still broken is an idiocy.write code with vi!, using debugger/ profiler make your code worse! and such kind of things is crazyThings change, c++ code can be written without memory leaks, and be as performant as needed.crazy 2004-10-28 8:56 pm Seems like a waste of time to make C++ in the kernel.If you were going to do it right, then just create a new kernel from scratch in C++.. 2004-10-28 8:58 pm am i the one of the few who do not have the Linus hero worship, and actually think he is very arrogant? why do people think just because Linus says it, it’s true? give me quantitive proof, not just knee-jerk reactions that might have been valid in ’91, but not 13 years later.i am curious, how much actual kernel development is done by Linus, and how much is done by others? 2004-10-28 9:11 pm Linus is the one that gets to say which patches go in the official kernel. If you want to run a kernel with this patch, you will have to do it yourself (btw many people run kernels with non official patches: video card drivers for example)The point is: working at the kernel level, you don’t *want* your memory management to be transparent to you. You *need* to know exactly how things like that are going to work. 2004-10-28 9:28 pm there is nothing wrong with an object oriented kernel.but that just wouldnt suit linux, its better for a kernel that is also highly modular. oop is just a way of thinking and could easily be implemented in normal c.linux will always be one big hump of code, closely tied together, with always changing “api”‘s or even “abi”‘s. 2004-10-28 9:44 pm You are both right, the kernel can be programmed in C++…seeing as how Linux is GPL’d; it would just take one person to fork Linux and start a new project, as well as rewrite it using C++!!!mv * > /dev/null 2004-10-28 9:54 pm This company is not a company, but a University 2004-10-28 9:57 pm I was under the impression that one of the major reasons for C++ not being used in kernel development was due to the different ways in which compilers mangle class names. This would make it impossible for modules compiled using (say) Intel C++ to be used with a kernel compiled with GCC. Heck, even with the same compiler, the name mangling isn’t guaranteed to be the same between releases. 2004-10-28 10:03 pm > hum I am not a kernel developer but saying after 12 years> that c++ compiler are still broken is an idiocy.Not really. The GCC ABI for C++ has been changing every major release of GCC. When the C++ ABI changes, C++ apps and C++ libs that you link to are in danger of breaking. The last thing you want is an unstable kernel. The GCC developers would like nothing better than to finally stabilize the ABI, but C++ just has too many features and special cases:http://gcc.gnu.org/ml/gcc/2003-10/msg00666.htmlAs for C++ in the kernel, I understand Linus’ reasoning. C++ hides a lot of things from the programmer. That’s okay in a userspace application, but it’s not okay in the kernel where transparency is important. You can’t optimize what you can’t see. A few K can make a huge difference in the kernel. C++ also provides many transparent features. Take exception handling as an example. C++ takes care of the details for you and does it’s own magic when something goes wrong. The problem is, what C++ wants to do may be in conflict with what actually needs to be done and you end up with a kernel crash. If Linux was originally coded with C++, these issues would have avoided through proper design and proper resource allocation idiom. But it wasn’t and trying to force fit it into the kernel will only lead to problems.That being said, if you could compile C++ so that it did not support “magic features” like exceptions, virtual functions, multiple inheritance, the new operator, or RTTI, Linus would likely be more agreeable to C++.After all, it would just be C with better encapsulation. The arguments about C++ ABI changes would also go out the window, since this part of the C++ ABI has been stable for ages. 2004-10-28 10:04 pm “If you are convinced that your favourite technique has value, you have to prove it. You can’t demand that other people spend the time explaining to you why they think it’s a bad idea. You have to do the hard work yourself to show you’re right. Code up a patch and benchmark it compared to the standard kernel. Be prepared to defend your patch in a broader context, and demonstrate that it doesn’t have costly side-effects.”from the lkm faqmakes sense if someone thinks c++ would be better for the linux kernel all they have to do is to prove it. 2004-10-28 10:11 pm Linus is not very specific with his comments. His trying to say, that (new) operator and (delete) operator can’t be implemented in kernel development.First you must develop memory managment functions, before you can use those operators in C++. This is the reason for not use C++ in the kernel. It’s the chicken and egg story.Thats all. If you don’t have new operator, why do you want C++? 2004-10-28 10:29 pm After all, look at the L3/L4 kernel series, where Jochen Liedtke argued that kernel designers couldn’t get IPC right because they didn’t fine-tune to the machine. (Liedtke prided himself partly on his assembly optimizations).Linus is totally right. C++ is taking C a bit higher-level, and that is good if all you want to do is write this or that app for userland. But the reason C is a typically-chosen kernel development language is precisely because of its properties as “high level assembly,” wherein hardware transparency is its best (and most useful) feature (for kernel development, anyway).He is also especially right that you don’t need an object-oriented language to write object-oriented code. Sure, OO code in C may be a little clumsy to those who are familiar with Java and C#, but you’ll get used to long_function_names and always passing a pointer to your object to every function. And if you use vim’s autocompletion facilities/taglist with exuberant-ctags, it shouldn’t be so bad :-). 2004-10-28 10:55 pm What I don’t understand is what is the POINT behind using C++ in the kernel.C++ is great for large projects. However, anything you put in the kernel should be absolutely minimalist, with any extra logic in userspace.C++ has the STL and lots of goodies that make quick projects quicker. But in the kernel, you don’t want to be using any of those inherently memory-hungry structures whose methods are not designed for low latency.The one thing that the kernel and C++ have in common is that they deal with lots of abstraction. It would be convenient to use inheritance, encapsulation, and polymorphism in the kernel. Of course, they already do that, and C++ won’t make it MUCH more convenient. Additionally, the sort of C++ you could wedge into the kernel wouldn’t be C++ but rather a restricted subset of C++.The whole reason that people want to use C++ in the kernel is because they can’t seem to shed their big-project mentality. (Also, they need the crutches provided by C++ because they can’t write clean C code.) If you find that C++ is the best language for writing your driver, then, by definition, you want to put the wrong sorts of things into the kernel. 2004-10-28 10:58 pm Writing kernel code in C forces to you simplify your way of coding. Anything that encourages simpler kernel code is good for the kernel. 2004-10-28 11:08 pm I think another reason that C++ is frowned upon in the linux kernel is that the whole language leaves a bad taste in kernel and other developer’s mouths.I’ve written more lines of C++ in my professional career than any other language, but there is something aesthetically unpleasing about C++ that just doesn’t sit well with me. There’s also the complexity of the language and various gotchas that bite even experience C++ developers. I think the simplicity of C gives it an appealing quality – you got functions, structures, macros, and that’s about it.C++ has its strengths. It’s fast, it does inherently support OO paradigms – even though the whole idea that OO is a panacea to all software woes has been way overblown. Templates are a powerful concept – even though in many other languages, the need for generic just isn’t there because of the dynamic nature of the language (Python).At this time I think my ideal choice of language for everything except very large applications would be Python with bits written in straight C for the hotspots. Next I would use something like C# or Java for larger applications if having a runtime dependency wasn’t a deployment problem.It’s not that I hate C++, it’s just not near my favorite. 2004-10-28 11:24 pm You do have a good point. I learned C quite quickly, and it is now my language of choice. However, when I started learning C++, I was greatly intimidated by it originaly. It never seemed as elegant as C did. 2004-10-28 11:36 pm C++ can make a good kernel language. A real life example is IBM’s AS400, which is written entirely in C++, and which has very widespread adoption throughout the business and government worlds, and has a very good reputation for being efficient and robust.Also, in most cases, any valid C code is also valid C++ code. So, theoretically speaking, one could compile the Linux kernel as is in g++ (or some other compiler), and it will compile and run fine with few alterations.C++ is not only a “high level”, OOP language. C++ allows you to get as low level as you want. You can do direct memory management, using pointers, etc. as much as you want in C++. C++ allows you to use OOP as much or as little as you want. C++ is a multi paradigm language, where you can make your code entirely procedural like C, or you can use generics (templates), or you can use OOP (and it’s powerful idioms like polymorphism, encapsulation, and inheritance).And in applying C++ in the Linux kernel, one could apply C++’s idioms where appropriate, like replacing the C object idiom with the more elegant object idiom in C++ (built into the language), or applying encapsulation and polymorphism, and applying low level C style memory management where appropriate. Also, C++’s exception handling is a powerful tool, but might not be appropriate for the kernel. But this does not mean you have to use it. In short, if one wants to apply C++ in the kernel, one can apply C++ features where appropriate, and apply C style code where appropriate. This could potentially make the source more managable in the long run.While it’s probably questionable as why someone would want ot incorporate C++ in the Linux kernel (other than as a cool intellectual exercise for C++ gurus, or in the long run to make the source more managable), C++ could potentially have benefits.I’m of the opinion that C is probably the best language for anything close to the hardware, like kernels. However, C++ can essentially do anyting C can, plus much more. I love both languages, and both have their strengths and weaknesses. But I believe that Torvalds is being a bit of an anti C++ zealot in his statements. 2004-10-28 11:42 pm I’m of the opinion that C is probably the best language for anything close to the hardware, like kernels. However, C++ can essentially do anyting C can, plus much more. I love both languages, and both have their strengths and weaknesses. But I believe that Torvalds is being a bit of an anti C++ zealot in his statements.—-he is only making the correct assertion the extra features offered by c++ and unneeded and wont be used in the kernel resulting in just using plain c subset anyway and this makes the feature redundant 2004-10-28 11:56 pm Um, almost. Unfortunately the C standardisation committee added things to the C99 standard that (unnecessarily IMO) made standard C less compatible with C++. Some of those things wouldn’t be that hard to handle, I think, like automatically mimicing C99 initializers with C++ constructors. But there are other issues that appear harder to deal with. Still, I’d love to see someone try, since C++ compilers typically are much better than C compilers at flagging things that probably won’t work. So if you have any code that is both C and C++ compliant, you’re definitely better off compiling it with a C++ compiler.I agree with the bit that Torvalds seems to go a bit overboard on his criticism of C++ vs C, though. OTOH, getting asked a certain question you’ve already answered 6 zillion times already probably doesn’t help… 2004-10-29 1:41 am When_All_Your Sentences_Look Like_Identifiers.Does Linus do this for effect or just force of habit, curious. 2004-10-29 2:09 am Of course you do realise that the current generation of L4 is programmed in C++ don’t you? 2004-10-29 2:36 am For a kernel, how about Embedded C++ (“EC++”):http://www.caravan.net/ec2plus/http://www.dinkumware.com/embed9710.htmlhttp://www.embedded.com/97/feat9712.htmFrom the article at dinkumware:Some of us are promoting it elsewhere as a more general solution to the growing complexity of C++.Anyone know if there’s a switch for g++ to enforce strict EC++? 2004-10-29 5:49 am Kernel coding in C++ is just like kernel coding in C: Powerful and elegant if you know what you’re doing, a big mistake if you don’t.AI: Using underscores is a way of _underlining_ text in ASCII. Just like asterisks are *bold*. 2004-10-29 7:37 am Posted by jeremy on Tuesday, January 20, 2004 – 16:48For the record, many more patches do not get into the mainline kernel because they don’t serve a majority. It means others can patch the kernel to include it (e.g. the developers).There’s far more interesting Linux kernel related news out there… 2004-10-29 8:08 am That kerneltrap bit lists all these responses about why C++ shouldn’t be used in a kernel.Not one response actually helping the guy who posted the problem.His problem: he has an absolutely massive module, written in C++. It used to compile quite happily for linux, and now it doesn’t.He wasn’t saying he wanted to replace the C kernel with a C++ one or anything. There are one or two minor annoyances in the linux kernel from a C++ compatibility point-of-view, struct namespace cited on the list for example, but otherwise there is nothing wrong with taking a module which does a lot of internal implementation in C++ and embedding it in an otherwise C kernel.On the point of view that kernels shouldn’t be written in C++, this seems shortsighted. Symbian, for example, is written in C++ and very nicely it works too. 2004-10-29 8:39 am Heh… Linus sounds like me a couple years ago, when I didn’t like C++.“Hiding allocations behind your back”… That’s a myth. If your type classes, that are supposed to live on the stack, are properly defined (which isn’t so much of a black art as some people seem to think), it all gets inlined and only specify implicit operations that you would otherwise have to rewrite everytime.“Object oriented code in C”… I used to do that, but really, it doesn’t make sense. It’s true you can apply about any programming paradigm with about any language, but it’s not as efficient, as easy and as clean.“Exceptions are majorly broken”… In which way ? I hope he isn’t thinking of the problem of destructing objects on the stack when you unwind the stack, as it proves that he doesn’t know C++ well enough. There are very elegant solutions to that, that help writing safer code even if you don’t use exceptions.The problem is that, writing proper C++ code. If you use C++ like it was C and spend your time fighting off the various features of C++ instead of working with them, then yes, C++ code is ineffective, ugly as hell, and you can shoot yourself in the foot without knowing it if you use exceptions. I used to write C++ code like that.One day, I started to write something and decided it would be better to use C++ instead of doing some half baked object code in C, as at least C++ is standard and can be way more readable. I thought “why not trying to do things the C++ way form the beginning ? It may not be so horrible”. And it wasn’t. I ended up with very compact, efficient, readable code, that was compiled as efficiently as if I wrote long functions instead of breaking things down in small classes. I did disassemble it to check it out.You anti-C++ guys should google “RAII” and tell me how programming this way could be inefficient, or how you wouldn’t know what the compiler is doing behind your back. And also, tell me how you would achieve to write code as safe when it comes to memory allocations and such, as easily, in C.The biggest problem of C++ is it’s not taught properly. Most people describe it as C, with classes, and a few extra bells and whistles like references. I used to be skeptical, but actually it’s very well thought and very coherent as a whole. You can’t just take one or two features of C++, ignore the others, and then say the language is broken because you think it can’t do XXX.Actually, I smile when thinking of my “C++ sucks” days. It reminds me of my “C sucks” days some years ago, when I was programming in assembly. I had about the same arguments against C that I later had against C++, and they all turned out to be wrong. 2004-10-29 9:16 am >This company is not a company, but a UniversitySince most universities in the USA are highly sponord and even routemapped by companies its allright to call it a company 2004-10-29 10:21 am Whatever about the rest of the language (and I think it’s one of the worst general purpose OOP ones out there, even Delphi is better), the exception handling has major problems. It’s not just stack unwinding and whatnot, but even managing memory in the event of an exception being thrown (this is why all other languages since Delphi have had “finally” blocks).See this article for more: http://www.octopull.demon.co.uk/c++/dragons/index.htmlThis is coming from an OOP fan who has lately begun to feel that of C and C++, C is the nicer to program in! 2004-10-29 11:52 am That’s pretty much what I meant (or rather, intended to mean )There’s only a handful of rule to follow to be exception safe, most of the time. Essentialy, never use regular C style pointers directly without a good reason and follow the RIAA (resource acquisition is initialisation) pattern as much as you can.Then you have more specific problems (like the ones described, and solved in the article you linked), but overall I think it’s a more convenient and less error-prone way to write code.You can forget to write a finally construct, while the compiler will never forget to destroy objects that fall out of scope.And object oriented code nicer to write in C ? I did, and it’s cumbersome. You write lots of extra stuff that would be done implicitely by a C++ compiler. It adds noise to the source, for no very good reasons. 2004-10-29 12:47 pm And object oriented code nicer to write in C ? I did, and it’s cumbersome. You write lots of extra stuff that would be done implicitely by a C++ compiler. It adds noise to the source, for no very good reasons.Uhmm…where did he say anything about OO code being nicer to write in C?In any case, writing function pointers in C (which would be pure virtuals in C++) is not that big of a deal. The messy part in doing OO in C is implementing inheritance, which is typically dealt with putting your parent object as the first member of your struct and then casting. I guess this is the way that Glib does it.Modern OO thought is to favor composition over inheritance and to program to interfaces – and doing that with straight C is pretty trivial.The linux kernel is OO anyway. Just look at any of the major data structures and see all the function pointers. C++ will just add needless abstractions and constant bickering over who has the best (overly complex) class hierarchy design.I think it was Knuth that said good code reads like literature (or something to that effect). More often than not, reading C++ code is like reading spaghetti code. You have to jump around all over in some brain-damaged, deeply nested hierarchy to figure out what’s going on. At least with Java and C# (which can easily suffer the same fate), you have a somewhat cleaner syntax.Sure, there is some good C++ out there, but more often than not, it’s overly obfuscated and cluttered with incomprehensible template code.I think at the end of the day, I just don’t like the way C++ looks from a visual perspective. That might sound weird, but that’s the way I feel. 2004-10-29 1:25 pm Uhmm…where did he say anything about OO code being nicer to write in C? Nowhere, I misunderstood you. Sorry.The linux kernel is OO anyway. Just look at any of the major data structures and see all the function pointers.OO doesn’t imply using function pointers. What about just having a plain structure and associate functions to it ? This is OO. In C, it forces you to adopt conventions like prefixing all your function names with the class name, and explicitely dereference all the member variables whenever you access them.What about access rights ? There’s no way in C to forbid access to certain members of a structure. You have to document them in some way, by adding a comment next to the mmbers you consider private. And its not enforced by the compiler, thus errors can creep up.The messy part in doing OO in C is implementing inheritance, which is typically dealt with putting your parent object as the first member of your struct and then casting.Inheritance by embedding structures into each other and casting… Well, I guess it’s ok if you are willing to do it. You can do anything. But again, it’s more error prone, and it adds noise (casts).Modern OO thought is to favor composition over inheritance and to program to interfaces – and doing that with straight C is pretty trivial. Yes, programming using interface is useful, but there are lots of cases where objects with zero runtime overhead, but that implicitely do various housekeeping stuff, are very useful. Or even, classes that are there only to keep your code from getting full of long and messy functions, but amount to nothing at runtime.Interfaces with virtual functions have a runtime cost, and these functions can’t be inlined. They’re not a silver bullet.And what about error management anyway ? You have to think of freeing resources everywhere, and C has no mechanism whatsoever to help you to do it. I don’t think it’s much better than an exception system, even if it has not so hard to avoid pitfalls.The linux kernel is OO anyway. Just look at any of the major data structures and see all the function pointers. C++ will just add needless abstractions and constant bickering over who has the best (overly complex) class hierarchy design.I understand your point, but I don’t think it’s really C++ fault. It’s more that since it allow to do these things more easily, it’s tempting to over-complicate stuff. I myself prefer straightforward code where I know what each classes actually do, and not have a vast amount of layers of abstraction if I don’t need them.Yes, you can do everything in C that you do in C++, like object programming and stuff.The purpose of C++ isn’t to let you do things that can’t be done in C, it’s to simplify your life. Indeed, it can complicate it instead, but not if used properly. 2004-10-29 3:29 pm Thanks for the insightful commentary MORB. 2004-10-29 5:11 pm Standard C++ is still the best language as far as core language features, but I think that C++ is best when using the C++ standard library, so it’s not right for the kernel. 2004-10-29 5:13 pm But I don’t think that C++ is just for OO programming, because of the use of generics (templates). 2004-10-29 5:22 pm I also think that Standard C++ has never been more useful than right now on Linux. It’s well suited for user mode library design, and (if there was more documentation) user mode applications. Standard C++ should actually move away from association with low level programming, yet it should not be a high level middleware language, it’s in the middle, and if there was more quality books and tutorials, than it would be the best language for user mode applications, it’s the most powerful general purpose language. 2004-10-29 5:35 pm Very insightful, intelligent comments about C++ MORB.I used to fear C++. I didn’t like C when I first learned it (all that pointer stuff). I like it now, a lot. Then I was hesitant to use C++, because it had “all that complicated OOP stuff” on top of the “messy C pointer stuff”.But once I learned it properly, I saw how powerful, easy, and productive C++ can be. This was thanks to reading and doing exercises out of “Accelerated C++” and of course Stroustrup’s book “The C++ Programming Language”.You are right MORBB. C++’s biggest problem is that it is not taught or learned properly. People apply C style coding to it, and throw in C++ extended features here and there, and get messy code in the process.The problem is often that people learn C first, then they foray into C++ (and apply the bad habbits). Perhaps people should learn C++ first, then learn C for when they need to go lower level, go more directly to the hardware. That’s how it’s done in “Accelerated C++” – the top-down approach. In fact, I wish all the C++ bashers out there would read “Accelerated C++”. It would be an eye opener for them. It was for me. 2004-10-29 5:37 pm All C++ bashers out there, please read the publication in the following link:http://www.research.att.com/~bs/new_learning.pdf 2004-10-29 5:40 pm They should get rid of John and Linus from Linux kernel development if they carry on with their elitist commentaries. 2004-10-29 5:42 pm Two arguments:1. Method/function names decoration. Decoration allowsfunction/method/operator overloading. I think that decorationis not standardised across compilers, maybe not even acrossthe versions of the same compiler. That could be the problemfor drivers and similar stuff that might not be compiled with gcc/g++. Example: icc (Intel compiler)2. When operators are overloaded, people sometimes get the strange idea of which symbol to use for particular operation.Other people have problem reading their code then. Since kernel is community project, it can create confusion.DG 2004-10-29 6:01 pm Apple is already using subset of C++ ( http://www.caravan.net/ec2plus/ ) in Mac OS X kernel :http://developer.apple.com/documentation/DeviceDrivers/Conceptual/I… 2004-10-29 7:03 pm I think mixing C and C++ would be a mistake.As for C++, I agree with the people above in that it is mostly misunderstood, one can write crap in any language.The comments from Linus are so 90’s, it’s embarrassing. 2004-10-29 7:09 pm Most of the time the Linux maintainers are the good guys, but once in a while they sound like a bunch of losers. 2004-10-29 8:02 pm OO doesn’t imply using function pointers.The essence of OO is polymorphism, which you can achieve in C through function pointers.What about just having a plain structure and associate functions to it ? This is OO. In C, it forces you to adopt conventions like prefixing all your function names with the class name,…I assume you’re refering to encapsulation, and I don’t see having to adopt a convention of prefixing your function with a object name (you’re not forced to) is a big deal unless you hunt and peck.…and explicitely dereference all the member variables whenever you access them. I assume you’re referring to having to pass in a pointer to structure and then using -> to dereference within a function. I don’t see how that’s a problem.What about access rights ? There’s no way in C to forbid access to certain members of a structure. You have to document them in some way, by adding a comment next to the mmbers you consider private. And its not enforced by the compiler, thus errors can creep up. Programmers should be using the public API. having public, protected, and private is no silver bullet.Yes, programming using interface is useful, but there are lots of cases where objects with zero runtime overhead, but that implicitely do various housekeeping stuff, are very useful. Or even, classes that are there only to keep your code from getting full of long and messy functions, but amount to nothing at runtime.Interfaces with virtual functions have a runtime cost, and these functions can’t be inlined. They’re not a silver bullet. You don’t pay for what you don’t use in C also…unlike Java where you’re relying on the runtime to be smart about all methods being virtual.And what about error management anyway ? You have to think of freeing resources everywhere, and C has no mechanism whatsoever to help you to do it. I don’t think it’s much better than an exception system, even if it has not so hard to avoid pitfalls. Exceptions are useful, even though it has been pointed out that C++ exceptions have some major warts.I understand your point, but I don’t think it’s really C++ fault. It’s more that since it allow to do these things more easily, it’s tempting to over-complicate stuff. I myself prefer straightforward code where I know what each classes actually do, and not have a vast amount of layers of abstraction if I don’t need them.Yes, you can do everything in C that you do in C++, like object programming and stuff.The purpose of C++ isn’t to let you do things that can’t be done in C, it’s to simplify your life. Indeed, it can complicate it instead, but not if used properly.Pretty much agree on these points. Shallow hierarchies and favoring composition are the way to go.I’ve written lots of C++ code in my lifetime (more than any other language). I think I somewhat grok proper OO. I’ve got Stroustrup’s 3rd edition I’ve got the GOF Design Patterns book, and think patterns are useful.I guess my biggest problem with C++ is the syntax, the overcomplification of the language that seems to stem from it’s legacy of needing to be C-backward compatible, can’t stand C++ streams, and think much of the standard library API is bad. 2004-10-29 10:34 pm You suck though, and people are better off to take the opposite of your advice as fact.