login
Header Space

 
 

Linux: C++ In The Kernel?

January 20, 2004 - 9:48pm
Submitted by Jeremy on January 20, 2004 - 9:48pm.
Linux news

A recent posting to the lkml requested help in porting the C++ Click Modular Router kernel module from the 2.4 stable kernel to the 2.6 stable kernel. The request was for ideas on fixing C++ related compilation errors, but the thread quickly turned into a lengthy debate on whether or not C++ had a place in the Linux kernel. The issue has been debated many times before, long ago earning its own entry in the lkml FAQ which offers numerous reasons why the kernel is not written in C++.

During the recent discussion, when it was suggested that perhaps the kernel is written in C simply because "we've always done it that way...", Linux creator Linus Torvalds joined in to explain:

"In fact, in Linux we did try C++ once already, back in 1992. It sucks. Trust me - writing kernel code in C++ is a BLOODY STUPID IDEA.

"The fact is, C++ compilers are not trustworthy. They were even worse in
1992, but some fundamental facts haven't changed: 1) the whole C++ exception handling thing is fundamentally broken. It's _especially_ broken for kernels. 2) any compiler or language that likes to hide things like memory allocations behind your back just isn't a good choice for a kernel. 3) you can write object-oriented code (useful for filesystems etc) in C, _without_ the crap that is C++."


From: Ashish sddf [email blocked]
To:  linux-kernel
Subject: Compiling C++ kernel module + Makefile
Date: Fri, 16 Jan 2004 13:09:24 -0800 (PST)

Hi, 
   I am trying to port a C++ kernel module from 2.4 to
2.6. (It is MIT Click Modular Router). 

   As I understand the module building has changed in
ver 2.6. I have got the Makefile to compile it but it
gives me lot of warning - all dependancies problem 

 It appears that the kernel Makefile treats it like a
host application and does not pass the necessary
processing routines.


  Does anyone can ideas about how to change the kernel
makefile to compile the C++ files the same way as C
files ? 


Any help will be appreciated. 


Ashish 


From: Richard B. Johnson [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Fri, 16 Jan 2004 17:07:05 -0500 (EST) If somebody actually got a module, written in C++, to compile and work on linux-2.4.nn, as you state, it works only by fiat, i.e., was declared to work. There is no C++ runtime support in the kernel for C++. Are you sure this is a module and not an application? Many network processes (daemons) are applications and they don't require any knowledge of kernel internals except what's provided by the normal C/C++ include-files. Cheers, Dick Johnson Penguin : Linux version 2.4.24 on an i686 machine (797.90 BogoMips). Note 96.31% of all statistics are fiction.
From: Bart Samwel [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Sat, 17 Jan 2004 13:59:20 +0100 Rest assured, ;) this is definitely a module. It includes a kernel patch that makes it possible to include a lot of the kernel headers into C++, stuff like changing asm :: to asm : : (note the space, :: is an operator in C++) and renaming "struct namespace" to something containing less C++ keywords. The module also includes rudimentary C++ runtime support code, so that the C++ code will run inside the kernel. I'm afraid that the task of compiling it for 2.6 is going to be pretty tough -- the kernel needs loads of patches to make it work within a C++ extern "C" clause, and it probably completely different patches from those needed by 2.4. Getting the build system to work is the least of the concerns. -- Bart
From: Richard B. Johnson [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Mon, 19 Jan 2004 08:46:54 -0500 (EST) I can't imagine why anybody would even attempt to write a kernel module in C++. Next thing it'll be Visual BASIC, then Java. The kernel is written in C and assembly. The tools are provided. It can only be arrogance because this whole C v.s. C++ thing was hashed-over many times. Somebody apparently wrote something to "prove" that it can be done. I'd suggest that you spend some time converting it to C if you need that "module". The conversion will surely take less time than going through the kernel headers looking for "::". Cheers, Dick Johnson Penguin : Linux version 2.4.24 on an i686 machine (797.90 BogoMips). Note 96.31% of all statistics are fiction.
From: Bart Samwel [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Mon, 19 Jan 2004 18:40:18 +0100 Just to make this clear: I'm not the original poster, so I'm not the one who is to be helped. I just happened to know the module, and I'd thought I'd give you a quick answer because I knew it. :) Now, let me try to add a bit of nuance to your suggested solution. Try porting 100s of C++ files (yes, it's that large) making heavy use of inheritance etc. to C. Then try to make a bit of C code usable as extern "C" in C++. Extern "C" was actually meant to be able to grok most C code, while C++ wasn't meant to be easily portable to C. So, for any moderately large module that uses any C++ features at all, it's probably easier to make small syntactic changes to the kernel than to port the module to C (which would amount to a full rewrite). I'll give you a bit of background about the specific situation. I'm not involved with the project, so I don't know all the details, but I do know the code and have worked on a "competing" system (as far as research systems compete). The choice for C++ for this project is really the most obvious choice, as the model is very OO. The module implements a router model that is configured as "clickable modules", i.e., very small elements with input and output ports and a bit of state that are connected to each other through small interfaces. Their element implementations are arranged hierarchically (as in C++ class hierarchies). I'm not familiar with the exact history of the project, but I expect that they decided to do C++ because the model they try to express is best modeled using C++. This design decision can be debated, because it is perfectly feasible (albeit with a lot more work) to implement an OO model in C. In fact, I have helped to implement a similar framework (the OKE CORRAL) which was written completely in C. But, the fact of the matter is, this useful (but huge) kernel module is there now (and it has been here since the early 2.2 kernels), and it was not written just to "prove" that it could be done, but because C++ seemed at the time to be the best language for the job. The start of this project may very well predate the many times that this was hashed-over on the LKML (disclaimer: I wasn't there, so I don't know). You refer to "what can only be" the arrogance of the writers, yet continue by claiming: > I'd suggest that you spend some time converting it to C if you need > that "module". and > The conversion will surely take less time than going through the > kernel headers looking for "::". Excuse me, but before calling somebody else arrogant, I would suggest that you might want check whether you're not calling the kettle black. It's not a sign of modesty when you assume without a trace of doubt that a module (that happened to have been developed over the course of four years by a team of people at MIT) is just a "\"module\"" and that it will take less time to port it to C than to make the kernel headers parse in a C++ extern "C" clause. In addition, imagine how you would feel if somebody referred to your work as a "\"module\""! The fact that you "can't imagine why anybody would even attempt to write a kernel module in C++" may just as well be due to a lack of imagination on your side, but in your statement I detect no trace of a doubt. And _yes_ you may very well be right about their initial decision being stupid (and you might not be -- I don't know), and _yes_ you are probably right about the whole thing being hashed-over many times (I don't know -- I wasn't there), and _yes_ there are people out there who would do anything just to prove they can do something others think is impossible or just filthy. So, yes, there _may_ be a point to what you're saying. _May_. I'm not saying you're wrong, and I'm not saying you're right. What I'm saying is that simply assuming that any C++ module is nothing more than a few lines of (de)glorified C and accusing the writers of being arrogant just because they wrote a kernel module in C++ is, in my opinion, jumping to conclusions based on technical-preference-turned-prejudice (at least, that's how it seems), and it's not very polite either. Unfortunately, this is how flame wars get started (as can be seen by the slightly agitated tone this message has taken, sorry about that! :) ). Just to make this clear to everyone: I'm not trying to instigate a flame war here about C vs. C++, as I don't really have an opinion on that subject. This posting has to do with my preferences w.r.t. personal style, and nothing with my technical preferences. -- Bart
From: Richard B. Johnson [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Mon, 19 Jan 2004 13:39:43 -0500 (EST) The possibility that something may have been written by some MIT people can't change the fact that C++ is not the tool that should have been used within the kernel. I once worked on a project at Princeton. That doesn't make me know anything about Relativity. Einstein didn't rub off due to some proximity effect. If the "MIT Team", as you so state, had actually inspected some kernel code, and actually understood what a Linux/Unix kernel does, then learned persons could not possibly have selected C++ for this project. If you review the project, you will probably also find that a large percentage of the code should have been implemented in user-mode (a daemon, or several). That's where C++ really shines. However, it wasn't. Which, to me, means that the developers were either clue-less or, once somebody actually figured out how a kernel works, it was way too late to change (an all to common problem). The number of persons who worked on a project does not affect the correctness of the tools nor the architecture chosen. Facts are not democratic. You can't vote them into or out of existence. > Unfortunately, this is how flame wars get started (as can be seen by the > slightly agitated tone this message has taken, sorry about that! :) ). > Just to make this clear to everyone: I'm not trying to instigate a flame > war here about C vs. C++, as I don't really have an opinion on that > subject. This posting has to do with my preferences w.r.t. personal > style, and nothing with my technical preferences. > This is not about preferences. Most software engineers wish that everything could be done using the first language they learned. Once they try to write a state-machine in FORTRAN (my native language), they begin to understand that there are other tools more suited for the job. Unfortunately, especially for students at well-known universities, learning a language often opens the door to a cult. I remember the "Pascal cult", the "forth cult", the "C cult" the "C++ cult", and now the "C# cult". Next year there may be "D" and the cycle will continue. Cheers, Dick Johnson Penguin : Linux version 2.4.24 on an i686 machine (797.90 BogoMips). Note 96.31% of all statistics are fiction.
From: Bart Samwel [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Mon, 19 Jan 2004 21:02:43 +0100 > The possibility that something may have been written by some MIT people > can't change the fact that C++ is not the tool that should have been > used within the kernel. I once worked on a project at Princeton. That > doesn't make me know anything about Relativity. Einstein didn't rub > off due to some proximity effect. No. But the fact that you haven't seen the module means that you can't possibly know whether the module is a "\"module\"" or just a "module" -- there are probably solid technical reasons to dislike C++ in the kernel, but that is no excuse to start calling things "\"module\"" instead of just "module". The fact that you're now attacking this minor point (the fact that these people happen to be MIT people) means that you missed the major point -- you were jumping to conclusions and calling people arrogant without checking the specific background, and without reserve. I usually think it's wise to *either* not check the background *or* keep no reserve, but not both. But that's just me. :) > If the "MIT Team", as you so state, had actually inspected some > kernel code, and actually understood what a Linux/Unix kernel does, > then learned persons could not possibly have selected C++ for this > project. > > If you review the project, you will probably also find that a > large percentage of the code should have been implemented in > user-mode (a daemon, or several). That's where C++ really shines. For most projects, you might be right. For this project, I think you're not. This project implements a new network router design, one that is aimed at achieving the best possible routing performance that can be achieved while maintaining maximum flexibility. The flexibility is achieved by having large amounts of configurable elements available, so that practically any routing task can be composed of the available elements. To achieve enough speed (and lack of latency) to be really viable as a router, they need to be as close to the hardware as possible. See it like this: as soon as pkttables can be moved to userspace with negligible performance loss, this app will be able to move too. > However, it wasn't. Which, to me, means that the developers > were either clue-less or, once somebody actually figured out > how a kernel works, it was way too late to change (an all to common > problem). The router code of the project works both in userspace and in kernel-space. It just works much slower in userspace. If they were able to get the right kind of performance in userspace they probably would. AFAIK these guys were also very early in the adoption of polling, according to the changelog they built polling support in April 2000. This got them a 4-5x speed increase. Not your typical project that you can make a daemon -- unless you're working in a microkernel OS, of course. Definitely not in Linux 2.2. > The number of persons who worked on a project does not affect the > correctness of the tools nor the architecture chosen. Facts are > not democratic. You can't vote them into or out of existence. The main point of that phrase was to indicate that more than four person-years went into this module. It didn't have anything to do with facts regarding correctness nor architecture, only with the fact that you stated without much reserve something that led me to believe that you had not considered that the size of this module may be larger than you imagined. >>Unfortunately, this is how flame wars get started (as can be seen by the >>slightly agitated tone this message has taken, sorry about that! :) ). >>Just to make this clear to everyone: I'm not trying to instigate a flame >>war here about C vs. C++, as I don't really have an opinion on that >>subject. This posting has to do with my preferences w.r.t. personal >>style, and nothing with my technical preferences. > > This is not about preferences. Most software engineers wish that > everything could be done using the first language they learned. Once > they try to write a state-machine in FORTRAN (my native language), they > begin to understand that there are other tools more suited for the > job. Unfortunately, especially for students at well-known universities, > learning a language often opens the door to a cult. I remember > the "Pascal cult", the "forth cult", the "C cult" the "C++ cult", and > now the "C# cult". Next year there may be "D" and the cycle will > continue. Yes, I know how this works. Although I have never programmed in FORTRAN, I have at least 15 other languages on my list (covering all of the well-known paradigms), not counting scripting languages, and I know that there is definitely a thing such as "the right tool for the right job". I do not dispute that. What I care about is your response, which seemed to indicate that you had already grouped the module authors in the "C++ cult" category, without keeping open the possibility that they might not be. You had already called them arrogant without checking any background. I don't care if they _are_ part of the "C++ cult", as you call it, but you had not enough information at this point to derive that. It seems that you're so allergic to the idea of mixing C++ with the kernel that you're blocking all possibility of discussion immediately. Calling somebody "arrogant" before they can even tell you why they did what they did is a perfect way to prevent any reasonable conversation from happening. It's not productive towards solving the problem at hand, and also not towards convincing people of your opinion. -- Bart
From: Richard B. Johnson [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Mon, 19 Jan 2004 15:37:46 -0500 (EST) On Mon, 19 Jan 2004, Bart Samwel wrote: > Richard B. Johnson wrote: > > On Mon, 19 Jan 2004, Bart Samwel wrote: > [... lots of text ...] [Snipped...] I stand by my assertion that anybody who develops kernel modules in C++, including MIT students, is arrogant. Let's see if C++ is in use in the kernel. At one time, some of the tools that came with it were written in C++ (like ksymoops). Script started on Mon Jan 19 15:19:33 2004 $ cd /usr/src/linux-2.4.24 $ find . -name "*.cpp" $ exit exit Script done on Mon Jan 19 15:20:25 2004 Well, perhaps the kernel developers were ignorant. They didn't write anything in C++. Maybe they were just too dumb to learn the language? Maybe there is another reason: The kernel development languages, as previously stated, were defined at the project's inception to be the GNU C 'gcc' compiler's "C" and extensions, and the 'as' (AT&T syntax) assembler. Anybody can search the archives for the discussions about using C++ in the kernel. Any person, or group of persons, who is smart enough to actually write some kernel code in C++, has proved that they are not ignorant. Therefore, they have demonstrated their arrogance. Cheers, Dick Johnson Penguin : Linux version 2.4.24 on an i686 machine (797.90 BogoMips). Note 96.31% of all statistics are fiction.
From: Robin Rosenberg [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Tue, 20 Jan 2004 01:59:22 +0100 måndagen den 19 januari 2004 21.37 skrev Richard B. Johnson: > Let's see if C++ is in use in the kernel. At one time, some > of the tools that came with it were written in C++ (like ksymoops). > > Script started on Mon Jan 19 15:19:33 2004 > $ cd /usr/src/linux-2.4.24 > $ find . -name "*.cpp" > $ exit > exit > Script done on Mon Jan 19 15:20:25 2004 > This is the "We've always used COBOL^H^H^H^H" argument. -- robin
From: Linus Torvalds [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Mon, 19 Jan 2004 22:46:23 -0800 (PST) On Tue, 20 Jan 2004, Robin Rosenberg wrote: > > This is the "We've always used COBOL^H^H^H^H" argument. In fact, in Linux we did try C++ once already, back in 1992. It sucks. Trust me - writing kernel code in C++ is a BLOODY STUPID IDEA. The fact is, C++ compilers are not trustworthy. They were even worse in 1992, but some fundamental facts haven't changed: - the whole C++ exception handling thing is fundamentally broken. It's _especially_ 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. - you can write object-oriented code (useful for filesystems etc) in C, _without_ the crap that is C++. In general, I'd say that anybody who designs his kernel modules for C++ is either (a) looking for problems (b) a C++ bigot that can't see what he is writing is really just C anyway (c) was given an assignment in CS class to do so. Feel free to make up (d). Linus
From: Bart Samwel [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Mon, 19 Jan 2004 22:24:39 +0100 Richard B. Johnson wrote: [...] > I stand by my assertion that anybody who develops kernel > modules in C++, including MIT students, is arrogant. > > Let's see if C++ is in use in the kernel. At one time, some > of the tools that came with it were written in C++ (like ksymoops). > > Script started on Mon Jan 19 15:19:33 2004 > $ cd /usr/src/linux-2.4.24 > $ find . -name "*.cpp" > $ exit > exit > Script done on Mon Jan 19 15:20:25 2004 Just so that you know, the extension .cpp is typically used by Windows C++ programmers, on most other environments the usual extensions are .cc and .C. If you look for *.cc you find scripts/kconfig/qconf.cc, so the kernel toolset is not completely C++-free. Not that all of this matters. > Well, perhaps the kernel developers were ignorant. They didn't > write anything in C++. Maybe they were just too dumb to learn the > language? It seems you you assume I'm an arrogant Bjarne-hugging C++-lover. Where did you get that? It's probably in your mind, where everyone who suggests C++ is a Bjarne-hugging C++-lover. I'M NOT IN THE C++ CULT. I'M NOT SAYING THAT EVERYONE SHOULD PROGRAM IN C++. Hope this came across, you are now officially declared deaf. ;) > Maybe there is another reason: > The kernel development languages, as previously stated, were > defined at the project's inception to be the GNU C 'gcc' > compiler's "C" and extensions, and the 'as' (AT&T syntax) > assembler. Anybody can search the archives for the discussions > about using C++ in the kernel. Yeah, definitely. I fully agree that it's not wise to use C++ *in the base kernel*. The Linux project needs to maintain overall consistency, and one of the means of doing that is using a small, well-defined toolset -- in this case, as and gcc. Any large project needs language and coding standards. But we're not talking about the base kernel here. We're not talking about migrating the kernel to C++, or even modules that are part of the Linux kernel source. We're talking about *independent modules*. The kernel exports a module interface, and any binary driver that correctly hooks into the interface of the running kernel (using the correct calling conventions of the running kernel) and behaves properly (e.g., doesn't do stack unwinds over chunks of kernel functions etc.) can hook into it and do useful work. If somebody has decided that it would be worth it for his project to use C++ (without exceptions, rtti and the whole shebang) then so be it, why should you care? It's just binary code that hooks into the module interface, using the correct calling conventions. It doesn't do dirty stuff -- no exceptions, no RTTI, etcetera. It compiles into plain, module-interface conforming assembler, that can be compiled with -- you guessed it -- 'as', the AT&T syntax assembler. Yes, they're taking a risk. Their risk is that C++ can't import the kernel headers, or that C++ might someday need runtime support that cannot be ported into the kernel. It's *their risk*, not yours. Then why do you have a reason to get religious about this? They're not submitting this stuff for inclusion in the Linux source! > Any person, or group of persons, who is smart enough to > actually write some kernel code in C++, has proved that > they are not ignorant. Therefore, they have demonstrated > their arrogance. This logic is faulty. It is built upon the premise that (ignorant || arrogant). Not listening to warnings of others is not a sign of arrogance per se, it is only a sign of the presence of a different opinion. It assumes that the kernel developers are always right, and that everybody who is smart should listen to them, on penalty of being arrogant. Yes, these C++-loving people may be wrong (or they may not be), but that does not _automatically_ make them arrogant, they may simply have a different opinion -- right or wrong. If they are wrong, they are not arrogant, but simply *stupid*. If they are right, they are not arrogant either -- they may be arrogant *about it*, but that's just a manner of behaviour, and it's up to them if they behave in this way or not. Kernel developers do not prescribe what people can do with the kernel, this is part of the essence of "free". And as a result of that, they do not have the right to declare people arrogant when they do not listen. They have the right to *call* them that, but the only result of that is that all discussion on matters like these are smothered in religious wars. And that's a pity. -- Bart
From: Richard B. Johnson [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Tue, 20 Jan 2004 10:20:53 -0500 (EST) On Mon, 19 Jan 2004, Bart Samwel wrote: > not. Kernel developers do not prescribe what people can do with the > kernel, this is part of the essence of "free". And as a result of that, > they do not have the right to declare people arrogant when they do not > listen. They have the right to *call* them that, but the only result of > that is that all discussion on matters like these are smothered in > religious wars. And that's a pity. It's not, as you say, a religious war. Whether or not one can use the back-end of a hatchet as a hammer does not qualify the hatchet as a hammer. Let me introduce the concept of a "learned person". Such a person might not actually exist. However, for my proposes, a learned person knows everything there is to know about solving the problem at hand. This is a definition. It is not subject to discussion. C++ was designed as an object-oriented language. C and assembler are procedural languages, as have been most all previous programming languages. The coding of operating systems is all about procedures. In fact, one of the reasons for the superiority of Linux is the great attention to the details of the actual execution mechanisms and the actual execution paths. An object-oriented language relies upon the compiler and libraries to work out the execution mechanisms to be used. The programmer is shielded from the actual mechanisms that implement the objects being manipulated. For instance, in C, one can code a loop counter and code the actual mechanisms by which a procedure may terminate. In C++, one may use iterators. Whether or not there is some actual counter is an implementation detail that can be hidden from the programmer. Of course one may also write C-like code when using C++ because there are some things that an object- oriented mechanism can't do by itself. This allows one to write loops with loop-counters in C++. The fact that C++ can be used somewhat like C does not make it a substitute for C anymore than a hatchet is a substitute for a hammer. Because of the object-oriented design of C++, there is considerable overhead necessary to make it function in an environment with many other objects. C has some overhead of its own, too. However, it is quite minimal. Local variable space is allocated simply by subtracting a value from the stack-pointer, for instance. The overhead of a particular language is often demonstrated by writing a simple "Hello World!" program in that language and then displaying the result as the size of the executable. This, of course, is quite unfair. It really shows how smart the linker is. A smart linker will link in only the required code. Linkers are pretty dumb. In the kernel, a linker doesn't have to be smart because the programmers have provided only the code that should be executed. There is no runtime library. Nevertheless, I provide three programs, one written in C, the other in C++ and the third in assembly. A tar.gz file is attached for those interested. -rwxr-xr-x 1 root root 57800 Jan 20 10:16 hello+ -rwxr-xr-x 1 root root 460 Jan 20 10:16 helloa -rwxr-xr-x 1 root root 2948 Jan 20 10:16 helloc The code size, generated from assembly is 460 bytes. The code size, generated from C is 2,948 bytes. The code size, generated from C++ is 57,800 bytes. Clearly, C++ is not the optimum language for writing a "Hello World" program. Because many persons don't know assembly language, it is probably not the best language either, in spite of the fact that the executable file is only 460 bytes in length. Therefore a learned person, given the task of choosing the language in which to write "Hello World!" would likely use 'C'. In spite of the fact that it can be written in C++, I suggest, in fact insist, that a learned person would never write such a program in C++ except for the purpose of demonstrating that it can be done. When writing code for a project, one is not usually presented with a bunch of languages from which one can choose on a whim, or by throwing darts. Instead, there are specific requirements defined by the nature of the work to be done. There is no learned person who would require that a data-base project be written in assembler. It is quite likely that the optimum language would be C++. There might be certain portions of the resulting executable that, in fact, were written in assembler, probably a lot of the runtime library. When writing a data-base program, one absolutely positively must not know what the underlying data-fetching mechanisms are because, once known and used to define (poison) the design, the program may run poorly on a network. This is one of the areas where object-oriented programming really shines. However, when writing code that runs in an Operating System, one is most entirely concerned, in fact consumed with the mechanisms by which the required functionality is obtained. Programmers spend hours, days, even weeks, shaving microseconds off from critical execution paths. This is because any resources used by the Operating System directly affect every task running under that Operating System. A learned person would never allow the code, defined by the designers of a compiler, to make the final decision about the mechanisms necessary to perform the required functions. Instead, the Operating System programmer makes those decisions. That's why a procedural language must be used in coding Operating Systems. The result of such attention to details is the Linux Operating System. Now, if you want to trash your copy of the Operating System with the output spewed from a C++ compiler, then I suggest you keep it real quiet. It is similar to "touching up" a famous painting with spray-paint, of defecating on a wedding cake. Again, writing a Linux kernel module in C++ demonstrates arrogance, absolutely, positively arrogance, and is an affront to the programmers who have dedicated major amounts of their time optimizing code execution in the kernel. Cheers, Dick Johnson Penguin : Linux version 2.4.24 on an i686 machine (797.90 BogoMips). Note 96.31% of all statistics are fiction.
From: Zan Lynx [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Tue, 20 Jan 2004 10:34:39 -0700 On Tue, 2004-01-20 at 08:20, Richard B. Johnson wrote: > Nevertheless, I provide three programs, one written in > C, the other in C++ and the third in assembly. A tar.gz > file is attached for those interested. > > -rwxr-xr-x 1 root root 57800 Jan 20 10:16 hello+ > -rwxr-xr-x 1 root root 460 Jan 20 10:16 helloa > -rwxr-xr-x 1 root root 2948 Jan 20 10:16 helloc > > The code size, generated from assembly is 460 bytes. > The code size, generated from C is 2,948 bytes. > The code size, generated from C++ is 57,800 bytes. > > Clearly, C++ is not the optimum language for writing > a "Hello World" program. I like C++ and hate to see it so unfairly maligned. Here's a much better example: Makefile: helloc: hello.c gcc -Os -s -o helloc hello.c hellocpp: hello.cpp g++ -Os -fno-rtti -fno-exceptions -s -o hellocpp hello.cpp Both programs contain exactly the same code: one main() function using puts("Hello world!"). # ls -l -rwxrwxr-x 1 jbriggs jbriggs 2840 Jan 20 10:02 helloc -rwxrwxr-x 1 jbriggs jbriggs 2948 Jan 20 10:06 hellocpp 108 extra bytes is hardly the end of the world. -- Zan Lynx [email blocked]
From: Richard B. Johnson [email blocked] Subject: Re: Compiling C++ kernel module + Makefile Date: Tue, 20 Jan 2004 13:10:21 -0500 (EST) Well you just fell into the usual trap of using the "C-like" capabilities of C++ to call a 'C' function. If you are going to use 'C' library functions, you don't use an object-oriented language to call them. That is using a hatchet like a hammer. I did not malign C++. I used it as it was designed and let the chips fall where they may. Cheers, Dick Johnson Penguin : Linux version 2.4.24 on an i686 machine (797.90 BogoMips). Note 96.31% of all statistics are fiction.



Related Links:

What a waste

January 21, 2004 - 1:09am

Wow. 30k of responses and not one of them offered to help the original poster. And Richard B. Johnson must have some serious blinders on. He's just not getting it.

What's to get?

January 21, 2004 - 1:40am
Anonymous

Really, the guy asked the kernel devs about C++. Kernel devs don't use C++. Do you expect many helpful replies?

yep, wrong mailing list.

January 21, 2004 - 1:51am
Anonymous

Nobody on lkml cares how many people write modules in C++. They decided long ago they don't want to waste their time with it.

The original poster actually got a lot of good replies as to exactly why nobody on lkml wastes their time with it.

No matter what Linus say

March 30, 2007 - 10:16pm
Oliver H.R. (not verified)

A good OS written on C++
http://www.unixlite.org/

Ha! Sooooo classic

January 21, 2004 - 3:46am
Anonymous

I can't think of any other single technical ssue where ignorance and bias is so widespread.

1) Exceptions can be disabled
2) C++ need not be used in an object-oriented style
3) Memory allocations "behind your back" is a non-issue; just develop your own memory-management routines.

The reasons for not using C++ hasn't got anything to do with how "good" or "bad" C++ is; it's simply a practical matter of Linux already being in C. Changing now would be harmful for consistency/coherency reasons - not to mention the fact that knowledge of C++ isn't omnipresent among existing developers.

Though humorously I'm sure if those other things weren't factors, the deafening Linux "cultural" bias would be enough to prevent C++ from being a choice anyway. :)

Be brave

January 21, 2004 - 3:50am

Submit these comments to lkml :-P

What's the point then?

January 21, 2004 - 4:09am
Anonymous

If we are going to disable exceptions, not use object-oriented style and develop our own memory-management routines, what would be the point of using C++, even if we were to rewrite Linux from scratch?

Re: What's the point then?

January 21, 2004 - 8:55am
Anonymous

> If we are going to disable exceptions, not use object-oriented
> style and develop our own memory-management routines, what would
> be the point of using C++

STL?

How much STL do you need in a kernel?

January 21, 2004 - 9:57am

Seriously? There are already lists and trees and hash maps in the kernel, fairly generic too so you can reuse them.

Another issue is the C++ ABI and GCC, there would have been at least 2 major breaks over the last few years should this exceptionless C++ be used.

I think a good rule of thumb may be that if it's something that C++ makes substantially easier (be it from code reuse or STL or whatever) then it may be something that is a good candidate for user space. I've simply never heard C++ advocated for kernel use by anyone who did a substantial amount of work in kernels. Sure, it might have some nice syntactic sugar but at the end of the day, more often than not, you want a portable assembly language for kernel tasks or the task you're trying to accomplish doesn't belong there. There is already a ton of generic code in the Linux kernel, it's very reuse centric, that may be made to look and read more cleanly with inheritance but it's already done in C and everyone understands the symantics of C very well.

You can read in an instant!

January 21, 2004 - 10:46am
Anonymous

I've simply never heard C++ advocated for kernel use by anyone who did a substantial amount of work in kernels.

There are kernels written in C++. For example the fiasco micro kernel. If you visit www.vfiasco.org you can see a paper right at the top of the page with the title "The Semantics of C++ Types: Towards Verifying low-level System Components". I did not read it but I think the title suggest which use C++ could have in a kernel.

The L4Ka::Pistachio (see www.l4ka.org) kernel is written in C++ too.

I know that

January 21, 2004 - 10:58am

There are Machs that have some C++ and the L4/Fiasco kernel is in C++. I think Spring may have been in C++ and there are probably numerous others.

Not to knock fiasco/L4 but it hardly seems like a blazing success that is causing people to reconsider using C++ in kernel space. Maybe I'll be wrong. It seems like just about all of the more popular production used kernels aren't using C++ in kernel space.

As someone pointed out, the increased type safty of C++ is a positive. I'd argue that we should add that to the next ANSI C standard though rather than start using a C++ compiler to compile the kernels.

RE: I know that

January 21, 2004 - 11:28am
Anonymous

You are right, these are all research projects. But it shows that C++ is a reasonable choice for kernels, although (or maybe precisely because?) hardly all features of C++ are used in these projects.
With regard to your comment that fiasco/L4 is not a blazing success yet: I have heard rumours that the GNU/Hurd project may use L4Ka in a (distant) future. These are rumours, but if I recall correctly they stem from a project member.

I, like you, think that increasing type safety in C a la C++ is probably a good thing. But as this will break compatibility between "old" and "new" C anyways , a even better step would be IMHO to make C a "real" subset of C++.

C as a subset of C++

January 21, 2004 - 7:12pm

C89 already is, for the most part, a subset of C++ (it's more accurate to say that they share a common subset, and that common subset is a big percentage of C89). The C99 standard broke that (since it was released after the C++ standard); I hope the next C++ standard will address this issue.

However, I don't expect that C will ever be a subset of C++. As a simple example, disallowing C programmers to use "class" as an identifier just because it is a keyword in C++ doesn't seem reasonable to me (though I would probably be hesitant use a C library that uses "class" in a header file).

The biggest issue in my mind, though is the ABI. Names of C++ functions that are in the global namespace are often mangled (so that they can be overloaded). C function names are usually not mangled; if this were to change, linking with old libraries that don't mangle function names would probably break. It was a pain when I couldn't link code built with g++ 2.95 and "2.96", then "2.96" and 3.0, then 3.0 and 3.2. I'd hate to go through that kind of pain all over again.

The biggest issue in my mind,

January 22, 2004 - 5:42pm

The biggest issue in my mind, though is the ABI. Names of C++ functions that are in the global namespace are often mangled (so that they can be overloaded). C function names are usually not mangled; if this were to change, linking with old libraries that don't mangle function names would probably break. It was a pain when I couldn't link code built with g++ 2.95 and "2.96", then "2.96" and 3.0, then 3.0 and 3.2. I'd hate to go through that kind of pain all over again.


Then don't bring name-mangling and function overloading to C. The extern "C" declaration exists precisely to modulate whether a given function adheres to the C++ or C linkage rules. In theory, you could have extern "F77" and extern "Pascal" linkage types and more for whatever languages you care about, too.

suppose the library was for m

October 31, 2004 - 1:08am
Anonymous

suppose the library was for making RPGs with.

enum class {"Warrior", "Thief", "Mage", "Cleric", "Monster", "God"};

or a custom app for a school.

struct class {
char *department;
char *number;
char *instructor;
char *timeslot;
char *location;
};

Kernels in C++

January 21, 2004 - 2:46pm
Anonymous

There is also eCos, an open-source embedded operating system. It is written in C++ and then presents a C API. As a person who dislikes C++ immensely yet writes code in C++ there are practical advantages to it; but most of those are only true if you don't already have a good knowledge base of how to do OO without C++.

If you already have that knowledge base (and the Linux kernel does) then there probably isn't much of a reason to go with C++.

OO without C++

January 22, 2004 - 10:25am
Anonymous

You mean "if you really enjoy doing the job of a C++ compiler, then there probably isn't much of a reason to go with C++".

You can write for()/while() loops with if() and goto. Would you do it ? Then why do OO without an OO language ? It's just as stupid, you're doing by hand what a compiler would do for you, except you'll go much slower and make many more mistakes.

Patterns matter, not OO

January 24, 2004 - 6:48am
Anonymous

Yeah, I've worked my way though Gamma. OO or not, patterns are what you really should be thinking in. And differently from those people simply memorizing the patterns, I've translated them all into plain c.

Guess what - they were simpler in c. A callback list is just *much* nicer than the observer pattern and does just the same with less than half the lines. Pretty much for any pattern, doing it in c instead of java saves me lines.

And unless you loose your taste or apply for IOCCC, fewer lines mean faster reading, less bugs or in short, better code.

Ok, your turn. Where again were the advantages of OO over c? Pick any language and example.

except C++ isn't OO

January 26, 2004 - 1:52am
Anonymous

Just ask the man that coined the term "object oriented". What he had in mind was Smalltalk-like. C++ can get it's own phrase.

More Kernels in C++

October 29, 2004 - 3:43am
Anonymous

And Symbian, which is very wide-spread in performance-critical embedded systems.

strong static typing and RAII

January 21, 2004 - 10:06am

IMO, C++ doesn't belong in the kernel, but there are some small advantages. Here are two.

Among other things, C++ provides strong static typing. While in C it is legal to write:

  char * x;
  int a = x;

it is probably wrong and it is not legal at all in C++.

The gcc compiler does a good job of warning the programmer about these issues if he uses -Wall, but this is not required by the standard.

Another nice feature of C++ is RAII (resource allocation is initialization). The idea is that when a resource (like memory) is allocated, an object is created. When that object is destroyed, the resource is released. For example, compare:

  int foo() {
    int success = 1;
    struct Foo * foo = kmalloc(sizeof(Foo));
    if(!foo) {
      success = 0;
      goto error0;
    }
    if(some_error_condition) {
      success = 0;
      goto error1;
    }
    do_some_work();
    struct Bar * bar = kmalloc(sizeof(Bar));
    if(!bar) {
      success = 0;
      goto error1;
    }
    if(some_error_condition2) {
      success = 0;
      goto error2;
    }
    do_some_work();
    struct Bar * baz = kmalloc(sizeof(Baz));
    if(!baz) {
      success = 0;
      goto error2;
    }
    if(some_error_condition3) {
      success = 0;
      goto error3;
    }
    do_some_work();
  error3:
    kfree(baz);
  error2:
    kfree(bar);
  error1:
    kfree(foo);
  error0:
    return error_code;
  }

with:

  int foo() {
    // Assume that an auto_kptr<> exists that works like auto_ptr<>
    // but uses kfree() instead of delete.
    // Also note that if allocation fails we aren't throwing an
    // exception like C++'s new does; exceptions don't mix with
    // kernel code.
    auto_kptr<Foo> foo = kmalloc(sizeof(Foo));
    if(!foo.get()) {
      return 1;
    }
    if(some_error_condition) {
      return 1;
    }
    do_some_work();
    auto_kptr<Bar> bar = kmalloc(sizeof(Bar));
    if(!bar.get()) {
      return 1;
    }
    if(some_error_condition) {
      return 1;
    }
    do_some_work();
    auto_kptr<Baz> baz = kmalloc(sizeof(Baz));
    if(!baz.get()) {
      return 1;
    }
    if(some_error_condition) {
      return 1;
    }
    do_some_work();
    return 0;
  }

IMO the C++ code is cleaner (and would be even cleaner with exceptions, but exceptions belong only in user-space).

Destructors!

January 21, 2004 - 7:02pm
Anonymous

I think you'd be very brave to use destructors like that. What if you needed to keep the objects alive after returning?

Also, with the goto method, you know exactly what is happening and in what order. Sometimes its of critical importance to clean things up properly.

Also, I hate to be a nit picker, but the C can be much more readable:

int foo()
{
    int success = 0;

    struct Foo * foo = kmalloc(sizeof(Foo));
    if(!foo)
        goto out;
    if(some_error_condition)
        goto out_foo;
    do_some_work();

    struct Bar * bar = kmalloc(sizeof(Bar));
    if(!bar)
        goto out_foo;
    if(some_error_condition2)
        goto out_bar;
    do_some_work();

    struct Bar * baz = kmalloc(sizeof(Baz));
    if(!baz)
        goto out_bar;
    if(some_error_condition3)
        goto out_baz;
    do_some_work();

    success = 1;

out_baz:
    kfree(baz);
out_bar:
    kfree(bar);
out_foo:
    kfree(foo);
out:
    return success;
}

Do you really know anything about C++ ?

January 22, 2004 - 6:31am
Anonymous

I think you'd be very brave to use destructors like that.

Hello, this is one of the most common C++ idiom.

What if you needed to keep the objects alive after returning?

Then you allocate the object on the heap of course. It's just like returning a pointer to any other kind of variable in C, if you want the pointer to remain valid, you malloc() it.

Also, with the goto method, you know exactly what is happening and in what order.

Same with C++. Just define your scope blocks the way you need them (supposing you really have to).

Sometimes its of critical importance to clean things up properly.

If the order of deallocation really matters, then it means that your data structures should be put into a class and the class' dtor should ensure that they are freed in the right order.

G. Laurent.

Do you really know anything about C++ ?

January 22, 2004 - 7:36am
Anonymous

> > What if you needed to keep the objects alive after returning?

> Then you allocate the object on the heap of course. It's just like returning a pointer to any other kind of variable in C, if you want the pointer to remain valid, you malloc() it.

Sorry, this doesn't work. The userspace function malloc() doesn't exist inside the kernel. You'll need to use something like kmalloc(), which takes an extra argument. kmalloc() needs to worry about atomicity of memory allocation, and whether or not it can use IO. Of course, if your object is too large, kmalloc() won't work either...

Many things taken for granted in userspace don't apply within the kernel. Unfortunately, C++ assumes too much about how its environment works. Using it inside the kernel is pretty silly as those assumptions are simply not true. (Even C has this problem in the loader code, where memory is being remapped all over the place causing the compiler to have a wrong understanding about what is going on - leading to all sorts of hacks to prevent certain 'optimisations' from being performed.)

Still easy to handle in C++

January 22, 2004 - 8:51am
Anonymous

This is what set_new_handler() is for, and why you have the placement new syntax (which allows you to provide your own memory, and have the object constructed in it, instead of making the C++ runtime allocate the memory), and why you can override the "new" operator.

Anyone that claims that C++ has unpredictable behavior is high overhead simply doesn't know C++ well enough - the C++ standard was developed according to a very strict guideline: You don't have to pay for what you don't use.

It's perfectly legal in C++ to use C memory management, and you can even instantiate C++ objects in that memory.

If you don't use virtual methods, your objects will take the same space as an equivalent C struct.

If you don't need exceptions, no code to handle them need be generated.

If you don't need (or can't) use iostreams for IO, you can ignore it, and any decent compiler will let you link with your own startup code and C++ runtime if you need to make sure you're not dragging it around.

If you don't need multiple inheritance, don't use it and there will be no thunks or other cruft messing up your code.

To summarize, you get what you decide is worthwhile for your application, and doesn't pay for the rest.

And you get the same reliability in terms of predictable memory management etc. as you have with C unless you SPECIFICALLY DECIDE TO DO SOMETHING ELSE. Nothing is magically allocated or deallocated in C. The memory management is well defined:
- If you call new, you will either end up in the class operator new, or in the new handler (which you can change with set_new_handler() if you have a particular need) - you have control over which by deciding which of these methods to use - and the default new handler will obtain memory.
- If you need a specific function to be called to obtain memory, you override operator new (if a specific class needs a specific type of memory) or change the new handler. The new handler can be 1-2 lines of code if you have simple needs.
- Objects on the stack are deleted when they go out of scope JUST LIKE IN C. The only difference being that destructors are called IF YOU HAVE DEFINED THEM.
- Objects on the heap are deleted when you call delete, just as if you'd called free() in C. Again destructors are called IF YOU HAVE DEFINED THEM.

Nothing is fundamentally different from C there. You can do all of what C++ does in C (there are still C++ compilers out there that generate C code instead of assembler, which is proof enough), and all of the features that set C++ apart from C are optional - you don't need to use them if they don't give you any benefits.

C++ doesn't assume anything about how it's environment works. Certain functionalities of C++ put specific requirements on the available runtime, but it's up to you whether or not they are suitable for your use, just like you don't go around indiscriminately using C libraries just because they are there, without evaluating if they are appropriate.

As for optimizations, that is a quality of implementation issue with regards to compilers, not a language issue.

set_new_handler

January 22, 2004 - 4:17pm
Anonymous

Let me clarify one thing. The "new handler" which is installed via set_new_handler is only used if the C++ runtime is unable to allocate requested memory on its own. Only then it is called. There is no default new handler. Thus your statement that you will "either end up in the class operator new, or in the new handler" is not entirely correct. In general, simply the default global operator new will be called if memory is requested.

But the tenor of your comment is of course correct.

Exactly

October 28, 2004 - 5:55pm
Anonymous

Well I think when they tried using C++ to code the kernel they cut off from the features they needed until they reached the bare minimun which was C :)

C++ doesn't assume anything

January 22, 2004 - 10:17am
Anonymous

You misunderstand : I was using malloc() as an analogy, I didn't mean it could be used in the kernel.

Contrary to what you think, C++ assumes very little, all memory allocation can be customized and made to fit your environment. There's nothing preventing you from allocating C++ objects with kmalloc().

C++ doesn't assume anything

January 23, 2004 - 4:53am
Anonymous

Actually, there is something... As said above, kmalloc() takes two arguments compared to malloc()'s one. kmalloc cares about what context you are allocating memory, malloc doesn't.

If you want to have generic constructors which allocate memory in the kernel, it is not nearly so clean as you say. You either must pass in the flags required by kmalloc() (and for all intents and purposes use C syntax for the call to the constructor), or you could stick to atomic allocations (which is really stupid, and liable to deadlock.) Or you could have a different constructor for each context... which is much cleaner written in C format, where you change the init function name, instead of the hack where you alter the constructors type/number of arguments in C++

C++ doesn't assume anything

January 23, 2004 - 6:00am
Anonymous

What you call a "hack" (namely method overloading) is used in all OO languages commonly used today (C++, Java, C#, Python, Ruby...). I think there's a reason why.

Second, it's perfectly possible to have named ctors in C++, that's yet another very common idiom (and yet another indication of how ignorant of C++ the people here arguing against it are).

Ruby does not have overloading

January 23, 2004 - 9:05am

It has dispatch based on the class of the receiver, but that's not the same as overloading. Because Ruby does not allow the types of parameters to be specified, there's no way for it to support overloading.

This may change in Rite (the Ruby 2.0 VM), but for now the closest Ruby comes to overloading is explicitly checking the types of parameters at run-time.

Placement new

January 24, 2004 - 2:50pm
Anonymous

You can solve that using the "placement new" construct, which was put in C++ for exactly this purpose. You can define a global new operator that takes a parameter, so that you can write things like:

mytype *m = new (GFP_ATOMIC) mytype (constructorparams);

The placement new operator is orthogonal to the constructor signature, so you can declare your constructors normally even when you've got a placement new operator.

wasn't it great when PC gave

March 10, 2007 - 2:00am
Home Bar Accessories (not verified)

wasn't it great when PC gave Mac the C++ programming guide for Christmas?

what the point is...

January 21, 2004 - 10:08pm
Anonymous

According to Bjarne (or maybe the C++ standardisation group) C++ is "as close to C as possible, but no closer". Apparently the C99 standard broke that, and that's not great. In my experience, tho, C++ compilers are a great help even with standard C. Why? Because C++ compilers tend to be much more:
- unforgiving in regard to code constructs that probably won't work than C compilers
- strict in regard to incorrect type conversions

Just those things can really help you find subtle bugs early on.

And then there's the 'using C++ as a better C' thing. C++ lets you declare variables at the spot you use them, instead of requiring you to define them at the beginning of a function. OK, this sounds trivial, but it helps make your code just that little amount easier to read and understand. And *that* can help big time...

C99 lets you declare variable

January 22, 2004 - 4:45am
Anonymous

C99 lets you declare variables at the spot you use them too.

the point of declaring variables where you use them

January 22, 2004 - 9:27am

The reason C++ lets you declare variables where they are used is not because of readability. In C++, an object's constructor is called when it is created, so there can be a significant cost associated with creating an object. In C, the main cost of creating an object is just stack space.

Readability is a nice side effect, of course. If you keep your functions short, however (which you should do anyway, IMO), this becomes much less of an issue.

what the point is...

January 22, 2004 - 10:27am
Anonymous

Although C won't let you declare variables at the point of use, C does let you declare variables at the beginning of any block. For example,


if (predicate) {
int i = 0;
for (; i < 10; i++) {
printf("%d\n", );
}
}

You can even do something like this in case you don't have an if.


{
int i = 0;
for (; i < 10; i++) {
printf("%d\n", i);
}
}

This is fine with me. Besides, knowing the intention of the variable is more important to me than knowing the type when I'm reading code.

You certainly DO NOT have to declare all of your variables at the top of your function. You can declare them at the beginning of any block within the function. This has been true for as long as I've been using C -- about 20 years.

what the point is...

January 22, 2004 - 11:42am
Anonymous

First, thank you for letting me know that the C99 standard lets you declare variables at the point of use. C++ 'captured my imagination' around or before '95, actually, so the work on the C standard didn't interest me quite as much as perhaps it should have.

About the whole declaring variables at the point of use thing, yes I did know that you can declare new variables simply by intoducing a new block scope. However, it's just ... well ... nicer that the *compiler* does it for you, instead of you having to do it on your own, legibility issues aside.

But that's just one trivial example how C++ can make your life easier. An other example is that it gives you the ability to maintain state within objects. You can do the same thing with C, but it is (or was, anyway) much less spelled out for you. The C++ standard spells out what you can or can't count on, the C standard didn't say much about things, so you just had to find out what worked with your platform and C compiler version... The story behind that is explained in 'Ruminations on C++', I don't recall everything about it, but that example involved how you could write a C parser. The author(s) of 'Ruminations' easily added support of the what I'll call ternary 'if' operator (example: a = b ? c : d;) to their C++ program. Someone who'd read that, it turned out, had been involved in a team that had tried to write a C parser in C ... apparently when they'd tried to handle the ternary 'if' operator, that's where their project failed, as C didn't spell out how to handle state (which C++ does).

Another example of C++'s ability to help you is the power of the constructor/destructor pairing. (I'll admit, I never realized how cool this is until someone explicitly explained it.) A lot of the time during programming you have to pair function calls, for example every malloc should be paired off with a free, every semaphore-lock needs it's unlock, every file-open needs it's file-close. Well, you can stop worrying about how to ensure that every resource aquisition call gets released as soon as you put those function-call pairs in constructor/destructor pairs. If I define an 'OnPaint' class with a BeginPaint call in its constructor and a destructor that calls EndPaint, all I have to keep in mind in my code that handles WM_PAINT is that I need to define an OnPaint object before doing anything else.

Anyway, those are just a few examples... as someone once put it: C lets you shoot yourself in the toe, C++ tries to help you avoid that. However, if you *do* manage to shoot yourself with C++, you'll be shooting your *foot* off. (And not just your toe! ;)

What good would C++ be?

January 23, 2007 - 10:20am
Lee Merrill (not verified)

Default parameters can be very nice, I wish standard C would implement this (at the moment, for a current program, I mean). Also, static constructors I would very much like to have right now for said program in progress.

> 3) Memory allocations "behi

January 21, 2004 - 6:53am
Anonymous

> 3) Memory allocations "behind your back" is a non-issue; just develop your own memory-management routines.

It's still pretty gross. Inside the kernel you need to be very careful about HOW you allocate membory depending on what type of context you're in (interrupt vs userland primarily; plus certain types of I/O processing have extra requirements) Since so much extra care is required I think that anything that makes allocation/deallocation more automatic is really asking for subtle bugs.

About 8 years ago I worked on a embedded project where I basically implemented a simple OS (actualy hosted on top of MS-DOS for file I/O but all non-storage devices were handled by my own kernel due to some rather specific requirements) I wrote it in C++ - the experience was sort of a mix. In some places C++ came in real handy (particularly the simple GUI I implemented; historically somewhere OO design really shines) However, when you're doing kernel code quite often you have generic callbacks (for interrupts, timers, etc) which is a pain. I ended up with dozens of little stub C functions that looked like:

void myobject_timer_callback(void *obj) {
((MyObject *) obj)->timer_callback();
}

I guess the technically correct way to do it would have been to have a new base class called "TimerUser" with a virtual function for a callback and use multiple inheritance or something (ugh!)

I still like a reasonable subset of C++ but now that I mostly do UNIX device driver stuff (linux and solaris) I'm perfectly happy to stick with just C.

I've watched this debate pop up regularly on LKML for the last several years - I think the consensus most people have is that C++ would only be acceptable if you were really careful to only use 5% of its featureset. At that point, using C++ provides so little added benefit it's just not worth it. Plus, imagine how much effort it would take to police people from sneaking in C++ features that weren't considered safe -- just look at how regularly floating point code sneaks into the kernel already.

Templates?

January 21, 2004 - 6:43pm
Anonymous


template <typename T>
void myobject_timer_callback(T& obj) {
obj.timer_callback();
}

Looks a lot cleaner to me.

I'd agree that exceptions don't belong into a kernel. Writing exception-safe code is pretty tricky.

I think you'll find templates

January 23, 2004 - 2:20pm
Anonymous

I think you'll find templates weren't really usable in C++ 8 years ago ;)

1) Exceptions can be disabled

January 22, 2004 - 6:05am
Anonymous

1) Exceptions can be disabled
2) C++ need not be used in an object-oriented style
3) Memory allocations "behind your back" is a non-issue; just develop your own memory-management routines.

Welll.. you use C++ compiler to compile C programs ...

Little question

March 7, 2004 - 2:29am
Anonymous

> 2) C++ need not be used in an object-oriented style

So, why the hell do you want C++?

Little answer

October 30, 2004 - 5:15am

>> 2) C++ need not be used in an object-oriented style

> So, why the hell do you want C++?

Metaprogramming?

click is a great tool

January 21, 2004 - 5:39am
Anonymous

I've played with click : it is a fantasticly innovative approach to modular router design, and C++ is the correct paradigm to implement the technology with encumbering it with "fake OO" C mechanisms.

I feel sorry for the negative comments above from the zealots. I feel Linus is also acting like a zealot here as his response hasn't been intelligent, but more of a arrogant throw back.

As I work with C++ daily, I can tell you that the amount "problems" you get with C++ are just as many as the amount of "problems" to get with C: they are just different types of problems. Take good design and good engineers, and everything is okay. Take the opposite, you get garbage (e.g. I've seen my share of spagetti awful lots of op-overloading C++; yet I've also seen my share of badly structured, unmaintainable, nasty-pointer, fake-things-with-macros C code).

calm down

January 21, 2004 - 7:02am
Anonymous

OK calm down and think about what you're saying. Then think about what Linus said. Then remember that Linus would be in the top handful of people most knowledgeable about C and kernel programming on the planet.

Then take a look at Linux's VFS for some encumbering "fake OO" code and enlighten us as to how you would unencumber it with C++.

Or, name one feature of C++ that would be of significant value to the kernel. No need for handwaving about "problems" and design, just 1 C++ language feature that would be of significant value.

No-one's suggesting C++ would

January 21, 2004 - 10:49am
Anonymous

No-one's suggesting C++ would be good for the kernel as a whole, the point is that the authors of the module in question felt (quite possibly rightly) that C++ offered a lot of advantages over C for what they were doing. Now, either the Linux kernel can be designed to make it reasonably easy to write a C++ module, or it can't; the decision between the two options should not be made by considering the irrelevant question of whether or not the entire kernel should use C++. This is precisely what Linus did, and he therefore failed to contribute anything of much significance to the discussion.

Linus' comment is irrelevant

January 21, 2004 - 11:30am

> OK calm down and think about what you're saying. Then think about

> what Linus said. Then remember that Linus would be in the top

> handful of people most knowledgeable about C and kernel programming

> on the planet.


Linus' comment is irrelevant. No one is advocating writing anything for part of the core kernel or kernel modules in C++. This module isn't intended to be part of the Linux kernel distribution. This is a special purpose program that needed a kernel. They felt that C++ was the best language to use for implementing their program. Then when they needed a kernel, they obviously felt that Linux was the best choice as opposed to writing their own and all the associated network card drivers.

Clearly, getting their module to work along with the kernel is going to be a good bit of work. As Bart Samwel pointed out in one of his messages:

... any binary driver that correctly
hooks into the interface of the running kernel (using the correct
calling conventions of the running kernel) and behaves properly (e.g.,
doesn't do stack unwinds over chunks of kernel functions etc.) can hook into it and do useful work.

So it doesn't matter if it's written in C++, assembler, or Modula-3 as long as the binary talks to the interface appropriately.

Yes it is

January 21, 2004 - 6:29pm
Anonymous

I'm sorry but it is. Read it again. Read the context. It was in response to someone who basically asked why there was no C++ in the kernel.

I think Linus is perfectly happy with people trying to use C++ in their patches or their trees if they want. He was responding why *he* doesn't like it.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
speck-geostationary