Slashdot Mirror


C++ In The Linux kernel

An anonymous reader submits "A researcher at Reykjavik University Network Laboratory (netlab.ru.is) has just released a Linux patch allowing for complete kernel-level run-time support for C++ in the Linux kernel, including exceptions, dynamic type checking and global objects (with constructors and destructors) The implementation is based on the C++ ABI in GNU g++, but contains various kernel level optimizations, that reduces the cost of throwing exceptions by an order of magnitude, thus making C++ exceptions viable in several scenarios. Furthermore, the Linux module loader is extended to handle weak symbols in C++, so that dynamic type checking is reduced to a pointer comparison, in contrast to string comparison."

850 comments

  1. nice by Anonymous Coward · · Score: 5, Funny

    how long until c# is supported?

    1. Re:nice by Yoda's+Mum · · Score: 1

      No, they're not rewriting the kernel in C#. That's absurd. The underlying core of Windows in longhorn will remain C++, with the UI and core API written in C#. This has been stated over and over again.

    2. Re:nice by 12357bd · · Score: 3, Insightful

      The core of Windows in C++? Maybe I am wrong, but If my memory serves me well, it was C and asm.

      --
      What's in a sig?
    3. Re:nice by myg · · Score: 4, Informative

      The core of Windows is written mostly in C. The GDI was written in C++ and the chief Kernel architect of WinNT (David Cutler) continually jabbed the Graphics group on their choice of C++.

      I don't suspect you will be finding C++ in NTOSKRNL any time soon. I think Cutler would beat up anybody who tried.

    4. Re:nice by Anonymous Coward · · Score: 0

      What makes you think GDI is written in C++? I can't find any evidence of that.

    5. Re:nice by character_assassin · · Score: 2, Funny

      If the GDI was written in C++, why isn't the API a C++ interface - or why doesn't it at least support one? That's screwy... but then again, we are talking about MICROS~1.

      --

      If you mod me down, I shall become more powerful than you can possibly imagine.
    6. Re:nice by Jugalator · · Score: 1

      how long until c# is supported?

      I hope the kernel will support QuakeC first.

      Would rock or what??

      "jsmith was destroyed by a bad USB driver"

      --
      Beware: In C++, your friends can see your privates!
    7. Re:nice by Anonymous Coward · · Score: 1, Informative

      IE's renderering engine is not used to display anything in windows explorer except when you open up html files using the file manager or use that stupid webview thing which wastes space by putting dumb shit on the sides and top of the listview by default.

      Can you give me a reference on DRM features being built into DirectX? If you mean the WMV codecs, that's not something anybody would consider DirectX.

      The kernel definitely will not be rewritten in C#. Maybe they'll add a subsystem written in C# way in the future but definitely the low level NT api will be in C with a few bits in assembly.

      Trolling, are we?

    8. Re:nice by russelr · · Score: 0, Redundant

      Ahhh....you read Showstopper, too.

    9. Re:nice by Scherf · · Score: 4, Interesting

      Probably because a C++ interface is a pain to access from any other language than C++. Or perhaps because the Win32 API is a C library and cluttering it by adding C++ interface would be much more screwy.

      Actually most APIs that need to be used by alot of people have a C interface, no matter in what language they where written in. Has nothing to do with them being "MICROS~1"...

    10. Re:nice by Anonymous Coward · · Score: 0

      Screw C#, how bout just plain ol VB. And Lisp, gotta have Lisp.

    11. Re:nice by Apro+im · · Score: 1

      I'm trying to figure out where the parent poster said he thought they were the same?

    12. Re:nice by Corngood · · Score: 3, Interesting

      Actually GDI+ has an extremely clean C++ interface. I was actually shocked when I saw it:

      http://msdn.microsoft.com/library/default.asp?url= /library/en-us/gdicpp/GDIPlus/GDIPlusreference.asp ?frame=true

    13. Re:nice by FuzzyBad-Mofo · · Score: 1

      I agree with you that this would be typical Microsoft behavior. However, C# (at least in .NYET) is byte-code interpreted, like Java, and not suited for Kernel work. I suppose it's possible they're working on a C# compiler that actually creates x86 instructions -- I don't know.

    14. Re:nice by myg · · Score: 3, Interesting
      Because in the late 80's and early 90's (when NT was written) C++ was quite new and the toolchains didn't have stable ABI's (not that we have a stable ABI today). So things like virtual function tables and such had no standard.

      Also, a C++ API is difficult to use if you are programming in C (or Pascal or FORTRAN, etc) where some languages don't have objects. Sure it can be faked, but thats exactly what the GDI API was, a front end for the C++ code underneath.

      So even though the underlaying implementations of pens, regions, patterns and such is in C++ you still deal with them via handles. In fact, technical issues aside a C++ GDI API at the time made no sense for another reason: Windows (16-bit) compatability.

      There was a big push by Microsoft to make the Win16 to Win32 converstion as much of a recompile as possible. Why else would we still have global and local memory? Such horrid things should have been dispatched to the land of the arcane years ago.

    15. Re:nice by Creepy · · Score: 1

      Not to mention c++ didn't really have namespaces or RTTI until ~mid-nineties (therefore, not sure if MS uses them). Virtual functions were pretty stable by the early nineties (when I started learning C++), but performance was pretty bad, IMO. I spent some time converting a flight sim from C to C++ at the time and had to rewrite large sections of code to not use virtuals after getting a 3x performance hit (probably more - I had numerous optimizations, as well) compared to the C equivalent due to the lookup table. Templates were pretty shaky (certainly no STL), and try-catch blocks were practically non-existent until the late 90s.

      Hrm... my understanding is that a handle (pointer to a pointer) is more for memory management than for interface. The idea is that you declare some objects as Handles, which allows Windows (or mac, as they originated there) to move the memory and the second pointer so that the move is transparent to the user and thus reduce memory fragmentation.

      Yeah, global memory is bad, and I somehow feel there is more to it than just backward compatibility to 16 bit, like maybe a lot of core code depends on it for performance reasons (e.g. interapplication communication). That's just a guess, though - I have no clue :)

    16. Re:nice by eeyore · · Score: 1

      About 12 months before Visual Basic is

  2. so... by Anonymous Coward · · Score: 0, Insightful

    for us non-developers, this means what?

    1. Re:so... by yecrom2 · · Score: 2, Insightful

      for us non-developers, this means what?

      Not a dang thing.

    2. Re:so... by Anonymous Coward · · Score: 0

      hell, it don't mean diddley squat to 99.9% of the so called "developers" out there...

    3. Re:so... by E_elven · · Score: 1

      I don't know. I don't personally mind C but I'd be much more inclined to write modules in C++.

      In any case, I think any application that uses the mentioned features of the language might get a boost too, from what I understood (didn't read the WP).

      --
      Marxist evolution is just N generations away!
  3. More Confusion by OverlordQ · · Score: 4, Funny

    So what will we say the kernel is written in . . C? C+? CKernelRun?

    --
    Your hair look like poop, Bob! - Wanker.
    1. Re:More Confusion by Short+Circuit · · Score: 1

      C/C++.

      And as an armchair advocate of distinction between the two, that scares me.

    2. Re:More Confusion by M51DPS · · Score: 5, Funny

      The kernel will be written in Java for more cross-platform compatibility.

    3. Re:More Confusion by Tumbleweed · · Score: 4, Funny

      CKernelRun?

      a) CKernelCrash
      b) CKernelPatchNotGetAcceptedByLinus

      One or the other, I'm sure.

    4. Re:More Confusion by aled · · Score: 3, Funny

      that's an exception:

      throw new ExceptionPatchNotAccepted("Linus");

      --

      "I think this line is mostly filler"
    5. Re:More Confusion by Anonymous Coward · · Score: 0

      N00b, we all know l337 coders use JavaScript and XUL for cross platform compatibility.

    6. Re:More Confusion by pyrrho · · Score: 2, Informative

      there can't be a distinction, C++ owes itself to an "improved C" mentality. C people can dissown C++ (except the parts that made it into ANSI C) but C++ people can't dissown C... and don't want to.

      --

      -pyrrho

    7. Re:More Confusion by Progoth · · Score: 1

      there can't be a distinction

      If you try to code C++ using the same methods, techniques, and constructs as you use to code C...then you're not a good C++ programmer. C++ does borrow massive amounts of C, yes, but they are definitely distinct languages.

    8. Re:More Confusion by pyrrho · · Score: 3, Insightful

      using C++ as a better C is the first step to enlightenment.

      Note: if you use ALL the techniques of C++ in your programs at the same time, then you are not a good programmer, period.

      --

      -pyrrho

    9. Re:More Confusion by Anonymous Coward · · Score: 0

      C++ and C are TWO MAJORLY DIFFERENT PARADIGMS, Dont bother applying here for work if you cant understand that. Next candidate plz.

    10. Re:More Confusion by torstenvl · · Score: 3, Insightful

      I struggled really hard with the choice to reply to your post or to use my mod points on this article.

      If your company refuses to hire people who refer to C/C++, then your company must not know what C++ is. If it did, it would a) Know that C++ is essentially a superset of C and therefore it is intelligent to make statements that apply to the dual entity referred to generally as "C/C++"; and b) You would have some kind of concept of class inclusion, and be able to understand that C and C++ are part of the same 'language family' -- it is therefore just as allowable to talk about C/C++ as it is to talk about 'Germanic' or 'Slavic' or 'Romance' or even 'Indo-European'.

      Such an overgeneralizing, bigoted, and asenine criterion is beyond all stupidity.

    11. Re:More Confusion by tomstdenis · · Score: 0, Troll

      Say who? C++ is not a better C anymore than my an iPod is not a better alarm clock radio.

      C++ and C solve different problems.

      IMO C is good for low level and structured [re: modular] programming. Despite what many think this isn't limiting to say kernel development. Sadly many "developers" think a 1000-line main() function is "impressive".

      C++ is meant to take C and throw it in an OOP direction. Although any program you can write in C you can write in C++ [and vice versa] this doesn't mean C++ is an "improved C". ...language wars aside...

      It's stupid comments like yours that really drive down the merits of actual computer science. Since you don't understand the issue you take up an irrational and off-base point of view. The problem is that the world is full of lazy stupid people just like you. They fill up the halls and next thing you know someone is leveraging your dynamic synergy between solution providers and contact base deployments!

      C++ has it's uses. C has it's uses. C++ is not "C v2.0".

      Tom

      --
      Someday, I'll have a real sig.
    12. Re:More Confusion by eidechse · · Score: 1

      You've obviously never read (or perhaps even heard of) the D&E.

    13. Re:More Confusion by eidechse · · Score: 1, Flamebait

      "C++ is meant to take C and throw it in an OOP direction."

      Wrong. It was designed to support a variety of programming paradigms. OOP only being one of them.

      "It's stupid comments like yours that really drive down the merits of actual computer science. Since you don't understand the issue you take up an irrational and off-base point of view."

      Nice screed. It'd be better if it wasn't based on incorrect information and shallow analysis.

      "The problem is that the world is full of lazy stupid people just like you."

      And pompous people who think they know something but clearly don't. And by clearly I mean that anyone who wants to can go get a copy of the D&E and see why you're wrong.

    14. Re:More Confusion by kjots · · Score: 1

      Actually, I would be interested to see the Linux kernel ported to the Java Virtual Machine. I don't mean re-write the kernel in Java, I mean port it; make it possible to compile from the original C sources into Java bytecode (wrapped up in a standard ELF file) and deploy in on a JVM using the JRE for interaction with the outside world. Then you could run Linux running on Java running on Linux running on Java running on Windows running on VMWare running on Linux running on oh no I've gone cross-eyed.

      Obviously it would be totally useless, but that's never stopped us before (think HTTP servers on Commodore 64s).

      Any takers? Didn't think so :)

    15. Re:More Confusion by ttfkam · · Score: 1

      And the next time I see a job listing that asks for a "slavic speaker" or "bilingual romance and germanic", I'll let you know.

      If C++ were a strict superset, standard practice wouldn't be to discourage use of char* in favor of std::string and fixed size arrays instead of std::vector.

      The way you use the languages is often times quite different so it seems perfectly reasonable to me that one would differentiate between the two on their resume. OOP and generic programming anyone?

      --

      - I don't need to go outside, my CRT tan'll do me just fine.
    16. Re:More Confusion by Anonymous Coward · · Score: 0

      What do you mean? My 5th level fighter/magic-user gonna take you down , homeslice!

    17. Re:More Confusion by Anonymous Coward · · Score: 2, Insightful

      I must say, that's a really lame argument. std::string is part of the std library not the language (it is written in C++, not part of it). You appear to be confusing symantics with syntax, convention with legal.

    18. Re:More Confusion by tomstdenis · · Score: 2, Informative

      Well the major difference between C and C++ being that C++ supports "native" classes while in C you emulate them with arrays of stuctures.

      A class is a way of organizing "objects" in a hiarchical manner. You could almost say an OOP manner. The fact you can do more with C++ doesn't take away the fact that oop is the major difference. In fact I can't think of any other reason to use C++ over C aside from classes and the various forms of inheritance.

      The point is C didn't borrow what C++ had to offer not because the ISO C committee is lazy or incompetent but that C solves DIFFERENT problems.

      --
      Someday, I'll have a real sig.
    19. Re:More Confusion by Anonymous Coward · · Score: 0

      no wonder you leaked...

      throw new ExceptionPatchNotAccepted("Linus");

      ExceptionPatchNotAccepted ex("Linus");
      throw ex;

    20. Re:More Confusion by I_Love_Pocky! · · Score: 5, Insightful
      In fact I can't think of any other reason to use C++ over C aside from classes and the various forms of inheritance.
      • Exception Handling
      • Function Overloading
      • Operator Overloading
      • New/Delete
      • Inline Comments
      • References (and pass by reference)
      • Others I'm sure
      C solves DIFFERENT problems.

      No, C solves problems differently.
    21. Re:More Confusion by tomstdenis · · Score: 0

      Your first three are part of OOP [hint: Java has them too]

      "new/delete" aren't programming methodologies they're overloaded functions for heap management.

      inline comments is part of C99

      pass-by-reference is not a programming methodlogy either... it's just a function of C++.

      Tom

      --
      Someday, I'll have a real sig.
    22. Re:More Confusion by I_Love_Pocky! · · Score: 3, Informative

      Your first three are part of OOP [hint: Java has them too]

      Sorry to break it to you pal, but you don't have to have classes to use these constructs, they work perfectly well with primitives and structs. Obviously they become much more useful in an OOP world, but they aren't part of OOP.

      pass-by-reference is not a programming methodlogy either... it's just a function of C++.

      No one said anything about programing methodologies. Your original post said:
      In fact I can't think of any other reasons to use C++ over C aside from classes and the various forms of inheritance.

      I just stated some language features available in C++ that aren't in C that are potential reason to use C++ over C (that aren't related to classes and inheritance).

    23. Re:More Confusion by frostfreek · · Score: 5, Funny

      And why not???

      With the GNU Compiler Collection able to generate machine code for Java, we'd be able to leverage all the things that Java excells at!
      Such as:



      umm....


      well,
      Oh forget it then.

    24. Re:More Confusion by cout · · Score: 4, Insightful

      C++ is not a superset of C. C++, C89, and C99 all share a common subset.

    25. Re:More Confusion by swillden · · Score: 1

      f your company refuses to hire people who refer to C/C++, then your company must not know what C++ is. If it did, it would a) Know that C++ is essentially a superset of C and therefore it is intelligent to make statements that apply to the dual entity referred to generally as "C/C++"

      Anyone who talks about C/C++ either (a) is speaking in a very broad context and is referring to C/C++ in comparison to say, C# or Java or Visual Basic; or (b) has a very shallow knowledge of the two languages.

      When the subject of discussion is languages for coding close to the metal, or when discussing the ability of specific programmers to write C or C++ code, the two languages should always be addressed as though they are distinct and essentially unrelated. Because they are.

      Sure, much (not all) C code will compile as C++. But that does not mean that a C++ programmer is qualified to write C or vice versa. The languages are vastly different in practice, with completely different sets of styles and idioms. A typical experienced C++ programmer who hasn't also spent a goodly amount of time writing straight C will find maintaining C code to be a terribly frustrating experience (I've been in that position, and learning how to do things "the C way" was not trivial). An experienced C programmer without significant C++ experience will be completely unable to decipher sophisticated C++ code.

      If someone tells me that they are a C/C++ programmer, I'm going to assume they're a novice at both languages. And it's a safe assumption. If I'm interviewing someone for a C or C++ programming position and they claim to have 5 years of C/C++ experience, I'll ask them what that means, just to be polite, and to give them a chance to redeem themselves, but in my head I know that the interview is probably already over.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    26. Re:More Confusion by Joseph_Daniel_Zukige · · Score: 1
      Sure, much (not all) C code will compile as C++. But that does not mean that a C++ programmer is qualified to write C or vice versa. The languages are vastly different in practice, with completely different sets of styles and idioms. A typical experienced C++ programmer who hasn't also spent a goodly amount of time writing straight C will find maintaining C code to be a terribly frustrating experience (I've been in that position, and learning how to do things "the C way" was not trivial). An experienced C programmer without significant C++ experience will be completely unable to decipher sophisticated C++ code.

      What? You mean people in the real world actually use C++ to do something besides write better CoBOL programs in C?

      Shoot. I've got to quit spending so much time at work and get out into the real world more.

    27. Re:More Confusion by eidechse · · Score: 1

      Congratulations! You just made the same type of over-simplification that caused you to go ape shit and flame the last guy.

      "In fact I can't think of any other reason to use C++ over C aside from classes and the various forms of inheritance."

      Which proves that you don't know nearly enough about either to have an informed opinion, much less call people lazy and stupid.

    28. Re:More Confusion by Anonymous Coward · · Score: 0

      Seems like a childish approach to me.

      And sorry, but if I was interviewing someone to be an interviewer, if they made silly distinctions like you're making I would certainly end the interview. A programmer should be able to pick up any language. If he's a good programmer and knows "C/C++" then he'll be able to work in either.

    29. Re:More Confusion by swillden · · Score: 1

      A programmer should be able to pick up any language.

      Sure, given time. But if I'm hiring an *experienced" programmer in a given language, it's because I want him/her to be productive immediately, not in a year.

      C++ is particuarly bad in this respect, because it takes at least two years to become really proficient.

      And, actually, I wouldn't really be dismissing the interviewee because of lack of skills, but because of lack of candor. Someone who claims 5 years of full-time experience and who *doesn't* distinguish between the two vastly different languages is almost certainly embellishing the truth to a level that I don't consider acceptable even in job interviews.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    30. Re:More Confusion by haruchai · · Score: 1

      I dispute this. It would depend on the type of language. I don't think that everyone is capable of mastery of just any programming language. I suspect there are those who have a natural affinity for procedural, functional or object-oriented.
      Also, I'd say that anyone who's been programming extensively in a particular language or a particular kind of language would probably have difficulty switching than a more inexperienced programmer.

      --
      Pain is merely failure leaving the body
    31. Re:More Confusion by Anonymous Coward · · Score: 0
      • Templates
    32. Re:More Confusion by Anonymous Coward · · Score: 0

      Linux already runs on the L4 microkernel which seems much more interesting and useful to me.

    33. Re:More Confusion by Anonymous Coward · · Score: 1, Insightful

      using C++ as a better C is the first step to enlightenment.

      No, it's the first step to hating C++. I was taught "C++" as a "better C", and nothing made sense. It was like mixing chocolate cake and ketchup. Both may be good, as long as they are kept separate.

      After that experience, I went to pure C, and found out that C is really a nice language.

      Later, I have learnt a few things about C++, real C++ this time, not "a better C" - and I started to see that if used right, C++ is a nice language too. As long as you DON'T use it as "a better C".

    34. Re:More Confusion by bartok · · Score: 1

      "References (and pass by reference)"

      That's also part of C

    35. Re:More Confusion by Viol8 · · Score: 4, Insightful

      Ah yes , but you can emulate most of that in C:

      "Exception Handling"

      setjmp(), longjmp()

      "Function Overloading"

      Function pointers

      "Operator overloading"

      Ok , you can't do this in C.

      "New/Delete"

      Its easy to create simple malloc()/free() wrapper functions.

      "Inline Comments"

      Eh? Whats stopping you doing /* waffle */ ?

      "References"

      These are hardly a selling point of C++ in my opinion. Implicit pass by address symantics should NEVER have been put in a modern language. Besides , after compilation they produce the same code as that using pointers.

      "Others I'm sure"

      Inheritance, templates etc. It just depends on how much you way syntatic clarity (C) against functional clarity (C++). Personally I think anyone who sticks religiously to either C or C++ without every using the other probably isn't a very competant programmer.

    36. Re:More Confusion by Anonymous Coward · · Score: 0

      Much too javaish, in C++ you simply use
      throw ExceptionPatchNotAccepted("Linus");
      (Exceptions are always thrown by copy.)

    37. Re:More Confusion by wtd · · Score: 2, Insightful

      Yes, you've aptly proved that it's possible to do many of the same things in C that you can in C++.

      However, the C++ way generally is more convenient, and I would go so far as to say that convenience, in the right measure, makes for better code. Rather than inventing your own wrappers for freeing memory, for instance, with "delete" all of that gets put into a destructor which can be easily found in any class that implements one.

      Obviously you can go overboard on syntax, but clearly if something becomes fundamental to the language, then there's a strong argument for adding syntax to support it, if only to prevent people from reinventing the wheel.

    38. Re:More Confusion by Anonymous Coward · · Score: 0

      C++ has it's uses
      C has it's uses

      "its".

    39. Re:More Confusion by TheRaven64 · · Score: 1
      Unlike Objective-C, which is a pure superset of C (i.e. any valid C program is also a valid Objective-C program). An interesting idea came up in discussion recently was to write a small microkernel which implemented Objective-C message passing at the kernel level and allow servers to be written in Objective-C. At the design level, it appears that we would not suffer from much of a slow down over a pure C kernel implementation, and the advantages in stability and maintainability of using a real OO language would be considerable.

      Implementing it is now number 376 on my to do list...

      --
      I am TheRaven on Soylent News
    40. Re:More Confusion by Anonymous Coward · · Score: 0

      paradigms. OOP only being one of them

      "paradigms, OOP being only one of them"

      if it wasn't based

      "weren't".

    41. Re:More Confusion by Anonymous Coward · · Score: 0

      Is that subset's name "Larry"?

    42. Re:More Confusion by Anonymous Coward · · Score: 0

      Sorry about that. I misinterpreted your post. Please ignore parent.

    43. Re:More Confusion by cow-orker · · Score: 1

      Any typical C program is an unidiomatic and generally bad C++ program, and vice versa. Face it, the languages are different. C++ may almost be a superset of C, but that means that C++ has different idioms and evolves into a completely different direction.

      My personal impression is that those self proclaimed "C/C++ programmers" write bad code in both these languages. They should stick to C/C++ and other hypothetical languages.

    44. Re:More Confusion by DrPizza · · Score: 1

      Actually, I think you shouldn't make such an assumption.

      The "C/C++" crowd seem to be made up of two kinds of people:

      a) C programmers who don't understand that C++ has a different featureset, different idioms, a much better library, and so on, and so who asume that C++ is still only "C with classes".

      b) people who know neither language particularly well.

      Neither group is particularly desirable, of course, unless you really only want C, in which case the first group may have some useful members.

    45. Re:More Confusion by character+sequence · · Score: 1
      A class is a way of organizing "objects" in a hiarchical manner. You could almost say an OOP manner. The fact you can do more with C++ doesn't take away the fact that oop is the major difference. In fact I can't think of any other reason to use C++ over C aside from classes and the various forms of inheritance.

      I think you're under-selling the value of objects. The fact that C++ includes deterministic destruction is very important for managing resources. Google for RAII or Resource Allocation Is Initialization (aka Resource Acquisition) to see what I mean. For me, this is the biggest win for C++ over C (and Java, for that matter).

      As others pointed out, you also missed templates, although in the case of an OS kernel I'm not sure how widely used they would be.

      --
      Karma: Nonnegative
    46. Re:More Confusion by glyph42 · · Score: 4, Insightful

      "References"
      These are hardly a selling point of C++ in my opinion. Implicit pass by address symantics should NEVER have been put in a modern language.

      Are you joking? References are the ultimate syntactic way to say "don't mess with the pointer, just use the object". The fact that you can't do arithmetic on references, or delete references, or assign references, without casting them in various ways is exactly the kind of friendly reminder that helps prevent a large class of common pointer-related programmer errors.

      Besides, after compilation they produce the same code as that using pointers.

      So does asm.

      Anyhow, C has got issues. C++ added constructs to automate many aspects of modern programming, the point being to help reduce bugs by giving friendly syntactical shortcuts and reminders, and writing some of the code for you. It's not an issue of what can and cannot be done; it's more of a likelihood of programmer error thing. C++ has issues too, mostly because of various odd syntactic decisions that were made, several of which stem from trying to make it backwards-compatible. Some of it is plain ugly :) But it sure as heck puts bread on my table without stressing my brain too much.

      Now I find myself evaluating the new Java, and C#, which both add even more features and little reminders to programmers to avoid common programmer errors. D is not looking too shabby, though it doesn't have anything like the market strength of either new Java or C#. Personally I think they are all getting bloated, adding too many keywords and not simplifying and unifying things enough. Back in my university days me and a buddy started designing a language we called D-, but we stopped after we realized how much time it would take to actually make it happen. I still dabble with the design on my spare cycles. Maybe some day... just maybe...

      --
      Music speeds up when you yawn, but does not change pitch.
    47. Re:More Confusion by Progoth · · Score: 1

      Note: if you use ALL the techniques of C++ in your programs at the same time, then you are not a good programmer, period.

      explanation please. I don't know that I buy that.

      One feature of C++ that I can think of that's probably not so good to use is RTTI, or at least using RTTI to dynamic_cast an object to do different actions based on what it is. It seems to me that that's bad OO design.

      Regardless, I don't see any way that your statement could be true.

    48. Re:More Confusion by ynohoo · · Score: 1

      surely you meant
      "writing more cryptic COBOL programs in C"?

    49. Re:More Confusion by ralatalo · · Score: 1

      Since you make ( or continue) the connection to other language usage like English...

      Do you list Written and Spoken English Separately..

      Sometimes... and sometimes C and C++ are very different but for a large number of purposes C and C++ are as close to each other as written English is to Spoken English. They both use a large number of common words, though there are some words that are only spoken and/or rarely written or commonly written and seldom spoken, and it can sometimes be really anoying to read something that was written in the manner of spoken English or listen to so formal document being read.

      I support both C and C++ compilers... so I look at both type of code... I actually use the C++ compiler for most of the C code because it works 99% of the time and when it doesn't work I can always test the C compiler and/or manually look at what's going on.

    50. Re:More Confusion by Viol8 · · Score: 0

      "References are the ultimate syntactic way to say "don't mess with the pointer, just use the object".

      Personally I find them to be more the case of "is this API function going to change my object or not?". Yes I know , use consts and make the code even more unreadable than it is already. Blech. Also duplicating an already existing method of doing something then removing most of its functionality seems IMO pointless. *shrug*

    51. Re:More Confusion by Corngood · · Score: 1

      const is unreadable??? Why are you a programmer?

    52. Re:More Confusion by freqres · · Score: 2, Funny

      But the real question is, are any of those methods better than GOSUB ?

      --
      Rampant Ninja related crimes these days...Whitehouse is not the exception
    53. Re:More Confusion by Viol8 · · Score: 1

      Its more syntatic waffle created to solve a problem that doesn't need to exist in the first place. It adds to the headache of trying to read complex C++ code.

    54. Re:More Confusion by Anonymous Coward · · Score: 0

      I have to reiterate the other poster's query: Why are you a programmer? Maybe you should take a position at the Gap.

    55. Re:More Confusion by Anonymous Coward · · Score: 0

      You're joking, right? Do you have the slightest idea of how selector resolution is implemented in an ObjC runtime?

    56. Re:More Confusion by Viol8 · · Score: 0, Flamebait

      Maybe you and the other poster (who is probably you anyway) should go get a clue in the real world of programming and start thinking for yourself instead of spouting childish antagonistic questions based on what you learnt on Programming 101.

    57. Re:More Confusion by I_Love_Pocky! · · Score: 1

      I really don't see why you feel that "const" does not belong in the "real world of programming." There is nothing complicated about it.

    58. Re:More Confusion by joggle · · Score: 2, Interesting
      consts are especially helpful in reading complex C++ code (so long as there are no const_cast functions or too many mutable variables). It is a nice way of telling whether a parameter is strictly an 'in' or an 'inout/out' using CORBA parlance. Nearly all of the code I've ever seen has far too few comments so syntatic sugar like this can greatly speed up comprehension of what the code is doing. It also makes it easier to port the code (well, interface anyway) to more strictly defined languages (like CORBA IDL). How can it possibly obfuscate the code? (with the premise that const_cast and mutable variables aren't used in abundance, which is bad programming practice anyway)

      It can be a pain in the ass to consistently use consts (because member functions called on const parameters must be const functions which in turn must only call const member functions) but I've never heard any complaints about reading the code.

    59. Re:More Confusion by Craig+Davison · · Score: 1

      Function overloading is not replaceable by function pointers, at least that I can see (I could be confused).

      Function overloading is the ability to define two functions with the same name, and the compiler knows which one a caller wants based on the parameters:

      blah *get_person (const char *name);
      blah *get_person (int age, int height);

      Also, malloc() and free() are pretty close to new/delete, but in C++, malloc() will not call a constructor and free() will not call a destructor. But I do realize you were talking about using free/malloc in C.

      And C++ doesn't have templates per se, but since it has multiple inheritance you could use a pure virtual class as your "template".

    60. Re:More Confusion by Anonymous Coward · · Score: 0

      "Exception Handling"
      setjmp(), longjmp()


      if (foo()==-1) return -1;

      "Function Overloading"
      Function pointers


      Yup. Trouble is that they are slow, but so are virtual functions. (In my book this is because because C++, like Java, isn't a true OO language, but some macro hack)

      "Operator overloading"
      Ok , you can't do this in C.


      Of course you can. You just have to manually pre/postfix functions with their argument types.

      "New/Delete"
      Its easy to create simple malloc()/free() wrapper functions.


      Well, duh. In fact you can do even better and use some efficient system instead. Like arena allocators.

      "Inline Comments"
      Eh? Whats stopping you doing /* waffle */ ?


      Two extra characters?-)

      "References"
      These are hardly a selling point of C++ in my opinion. Implicit pass by address symantics should NEVER have been put in a modern language. Besides , after compilation they produce the same code as that using pointers.


      I have an impression that references are in C++ due to a necessity rather than clarity, something to do with operator overloading etc.

      "Others I'm sure"
      Inheritance,


      Overrated. Proxying is a much more general concept and avoids a myriad of odd semantic problems.

      templates etc.

      You can do incredible things with #include/#define ;)

      It just depends on how much you way syntatic clarity (C) against functional clarity (C++).

      The problem with C++ with stuff like kernels is that it forces its own way of implementing things. Sometimes it just doesn't meet the needs. For example, what if you needed to refer to object data and vtable with a pair of pointers instead of storing the latter in the object?

    61. Re:More Confusion by Anonymous Coward · · Score: 0

      Ok, what does const do in C?
      12 poeng hint: it's not the same as in C++.

    62. Re:More Confusion by pyrrho · · Score: 1

      you have a good point. I think references are probably best left to operator overloading, usually, and not library or function calls in which it would be better to request a pointer and be more obvious to the user/caller how you will handle the object.

      --

      -pyrrho

    63. Re:More Confusion by pyrrho · · Score: 1

      >(with the premise that const_cast and mutable variables aren't used in abundance, which is bad programming practice anyway)

      a lot of people object to the fact that you can break the rules at all.

      >(with the premise that const_cast and mutable variables aren't used in abundance, which is bad programming practice anyway)

      yep... I'll admit I've often been lazy about using const (and get called on it) becuase it takes care to use and not get screwed this time or that time yada yada (peanut gallery: shut up, I admitted it was lazy... it's not hard)... but the point is, doing it makes it easier for the user of your code... it's part of the contract with the user right there in the declarations, with a compiler to help enforce it.

      --

      -pyrrho

    64. Re:More Confusion by Carewolf · · Score: 1

      C++98 was designed to be a good superset of C89. The C++ standard has not yet been updated to incorperate C99, but they mix fine in gcc and most other C++/C99 compilers, so in practice C++ is always a superset of C.

    65. Re:More Confusion by pyrrho · · Score: 1

      >Yup. Trouble is that they are slow, but so are virtual functions. (In my book this is because because C++, like Java, isn't a true OO language, but some macro hack)

      C++ isn't supposed to be a true OO language. Stroustrup doesn't like telling people what idiom to use and doesn't believe in one paradigm to rule them all.

      >I have an impression that references are in C++ due to a necessity rather than clarity, something to do with operator overloading etc.

      you got that right

      >>templates etc.

      >You can do incredible things with #include/#define ;)

      I didn't know until recently that this was exactly how templates came about... from the experience of using CPP macros to do generic programming. The only part of C that Stroustrup is really against (but by no means has the C++ standards committee been as against), is the C preprocessor. Still, I think templates are nothing but macros on steroids. Of course, it's nice that the compiler is doing this which yields a lot of advantages.

      >The problem with C++ with stuff like kernels is that it forces its own way of implementing things. Sometimes it just doesn't meet the needs. For example, what if you needed to refer to object data and vtable with a pair of pointers instead of storing the latter in the object?

      I don't get this. Why couldn't you do that if you need to? You would have two data structures. Obviously you would manipulate the vtable yourself... because you chose to, so you would not use C++ syntax to invoke those functions... except that with your class definition you could still create very convienient and efficient syntax for calling these functions.

      In the end, the fallback is that C-style code is a part of C++... C++ is not some pure language trying to stop you from writing C-style when that's the best thing. Quite the contrary, C++ has bent over backward to secure and guarantee you could do just that!

      --

      -pyrrho

    66. Re:More Confusion by pyrrho · · Score: 1

      to each his own.

      frankly... minimal C++ use to me is C with the class construct, constructors and destructors... which of course is not just as better C.

      --

      -pyrrho

    67. Re:More Confusion by cout · · Score: 1

      There are a number of cases where a valid C program is not a valid C++ program. The easiest example is a program that uses "class" as an identifier; it will work fine with a C compiler, but it will fail to compile in C++, as "class" is a reserved keyword.

    68. Re:More Confusion by pyrrho · · Score: 1

      C++ is a multiparadigmed language, one of the paradigms is the set of paradigms available in C.

      That's according to Stroustrup. Believe me when I say I don't want to apply to work there. Next Coward plz.

      --

      -pyrrho

    69. Re:More Confusion by ttfkam · · Score: 1

      Yes and char* is a convention as well -- simply one agreed upon by the original C coders. Check out *any* article, book or note on C++ since 1998 by Stroustrop, Josuttis, Alexandrescu, etc. and you will see that char* is strongly discouraged in favor of std::string. The fact that it's part of the standard library is an implementation detail, not a comment on optional use.

      With modern STL implementations, you have basically no advantage using char* or fixed size arrays in most code.

      --

      - I don't need to go outside, my CRT tan'll do me just fine.
    70. Re:More Confusion by ttfkam · · Score: 1

      Try Queen's English to American English. As John Cleese once said when asked the difference between Americans and the English, "We speak English. You don't."

      Bring in some colloquialisms from the South and compare them to the rhyming slang of parts of England and you'll have a closer analogy. Technically they are both speaking English, but there are massive differences that make communication quite difficult.

      And as point of fact, my written and spoken English are quite similar. I haven't quite decided whether that means I have a particularly lucid form of writing, that my speech is more stilted or that most people just can't write for shit. In any event, your analogy was lost on me.

      While C++ may have started as a preprocessed language on top of C, it has since continued to diverge to the point where it cannot be seen strictly as a superset anymore. In other words, it has been transitioning from being just a dialect to a noticeably different language with different traits and different idioms.

      Also, be careful when you say such things as "I support both C and C++ compilers." It has the implication that you develop production compilers. If this was the case, you would have seen the tremendous difference in implementation between the two.

      --

      - I don't need to go outside, my CRT tan'll do me just fine.
    71. Re:More Confusion by eidechse · · Score: 1

      You're absolutely correct. Thanks.

    72. Re:More Confusion by fnj · · Score: 1

      Ah yes , but you can emulate most of that in C:
      "Exception Handling"
      setjmp(), longjmp()


      Setjmp is in no way comparable to C++ exceptions. The essence of C++ exceptions is the way automatics on the stack are magically cleaned up. And if you use smart pointer automatics, you can clean up stuff on the heap. This is key to preventing memory leaks. Setjmp offers no way to do this.

      "References" ... they produce the same code as that using pointers.

      The point is not what they compile to, but that they are safer as well as syntactically nicer. There is no reference arithmetic like pointer arithmetic. With pointers, there is nothing to ensure that the pointer will always point to a valid object.

    73. Re:More Confusion by swillden · · Score: 1

      Good point.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    74. Re:More Confusion by Anonymous Coward · · Score: 0

      Carewolf no, in practice C++ is NOT a superset of C because most C programs won't compile under C++ compiler without changes. Simple example:

      char *p = malloc(10);

      This will compile under C compiler but won't compile under C++ compiler. Casting return value of malloc is not recommended in C for several reasons.

    75. Re:More Confusion by Anonymous Coward · · Score: 0

      uga... exception handling in C++ is totally different compare to setjmp/longjmp. setjmp/longjm is just a jump after all.

      and pleeeeeeese don't even mention templates! that's just stupid way to implement generics.

      I mostly agree with "you can do most of C++ things in C", though.

  4. C++? by Anonymous Coward · · Score: 5, Funny

    Good now I can fire up my good old visual basic and hack the kernal with COM.

    1. Re:C++? by npietraniec · · Score: 3, Funny

      and I was just thinking... I wonder how long until someone makes a "I want to use visual basic" comment. That didn't take long. hilarious.

    2. Re:C++? by FecesFlingingRhesus · · Score: 2, Funny

      No no one would ever want VB, now C# or java on the other hand.

    3. Re:C++? by Anonymous Coward · · Score: 0

      Java, NO!
      C# I don't know enough about. It might be possible, if you didn't use most of its features.

    4. Re:C++? by Anonymous Coward · · Score: 0

      I would want a VB kernel, you assholio!

      Po0p dick is a result of anal sex!

    5. Re:C++? by FecesFlingingRhesus · · Score: 1

      It was actually just a joke. I don't believe either have their place in the Kernel.

    6. Re:C++? by Electroly · · Score: 2, Interesting

      Interestingly, the driver interface in Mac OS X actually is COM. With QueryInterface() and everything.

    7. Re:C++? by Kethinov · · Score: 2, Funny
      Imagine the enormity of newbie kernel hackers if such a thing were beieved to be possible...

      I can imagine a post to usenet now...
      Subject: this damn thing wont compile

      omg why are none of my win32 api calls working this sucks this will never be better than windows
      And the ensuing reply...
      Subject: Re: this damn thing won't compile

      Uh huh. Well. It won't compile because your api calls are, uhm, frozen. Yeah. You need to unfreeze them. There should be a blue liquid in the trunk of your car called antifreeze. If you drink it all, and I do mean all of it, you'll be able to unfreeze your api calls.

      Have fun.
      --
      You're right, I wouldn't steal a car. But if it were possible, I sure as hell would download one!
    8. Re:C++? by Anonymous Coward · · Score: 0

      Actually you are not completely correct. Java or C# are type/memory safe languages which allow safe programming. There are some plans in the company where I happen to work to move linux kernel into user space to run it on a kind of platform similar to Java or C# (I am posting anonymously for a reason so I don't want to give any more details either, I just personally believe it is possible).
      So your joke was not far from what may happen. Not tomorrow, maybe 4-5 years later.

    9. Re:C++? by arkanes · · Score: 2, Interesting

      COM is a documented standard and as object models go it's not bad. Better than CORBA, anyway.

    10. Re:C++? by Anonymous Coward · · Score: 0

      > Interestingly, the driver interface in Mac OS X actually is COM. With QueryInterface() and everything.

      The components of OSKit are also connected with COM. COM's nice, just that MS wanted to use it in grossly inappropriate ways instead of updating DDE to modern demands.

    11. Re:C++? by strider44 · · Score: 1

      It's a Bastard Operator From Hell field day.

    12. Re:C++? by Anonymous Coward · · Score: 0

      Actually COM is based on C. It provides an object-like interface to pure C code. It is not C++.

      That's what is was developed for, so that you can use an object model but get the benefits of the C ABI for interfacing various components and doing remote stuff. (you know, because C++'s ABI was fucked up by not being standardized)

    13. Re:C++? by HFXPro · · Score: 1

      Doesn't that kind of negate the idea of user space and kernel space? I can see maybe some pieces of the kernel being in user space. However, for the main task of what a kernel is supposed to do (schedule, manage, I/O)... I don't know why that would be user space.

      --
      Reserved Word.
    14. Re:C++? by kaffeine · · Score: 1

      Drivers in the Mac OS X kernel (xnu) use IOKit, an object object orientated device driver framework using embedded C++ (C++ minus exceptions, templates, mutliple inheritance + other stuff).

      In this case using C++ at this level in the kernel allows devices to simply inherit most features from base classes (ie/ an ethernet driver can subclass IOEthernetController).

      see http://www.kernelthread.com/mac/osx/arch_xnu.html

    15. Re:C++? by Anonymous Coward · · Score: 0

      In this case using C++ at this level in the kernel allows devices to simply inherit most features from base classes (ie/ an ethernet driver can subclass IOEthernetController).

      How is this any better than simply using a struct of function pointers? C++ (Even embedded C++) would seem to be overkill if all you really need as classes and some basic inheritence.

    16. Re:C++? by Anonymous Coward · · Score: 0

      Why do get so bent out of shape whenever someone makes a joke or disparaging comment about Microsoft (which, BTW, they arguably richly deserve)? Could it be that you're just a flaming MS fanboy?

      Naw, that couldn't be it, since everything you write is "fair and balanced" and well thought out.
      </sarcasm>

  5. Alright!! by 21chrisp · · Score: 5, Funny


    I'm sure the kernel developers will LOVE the idea of putting C++ in the kernel.

    1. Re:Alright!! by Bloater · · Score: 5, Insightful

      Why ever not? C++ allows for much better code, you just need a compiler that's up to the task, and runtime ABI that is predictable. Granted, standard C++ may not be appropriate, but with some features disallowed, it is ideal (better than C).

      All you need is policy that covers use of various features, just like the Linux kernel requires policy on use of C.

      multiple platform support becomes template specialisation, locking rules can actually be enforced by the language (ie, to get member functions to access an object, you can require that you call a member function to return a mutex object which has the members, and when that mutex is destroyed naturally, the lock is freed. fast, safe, secure.

      The question is how customisable is the compiler for how virtual functions, etc, are implemented. Those are the only issues to be concerned about because C++ is plain better than C.

    2. Re:Alright!! by metalogic · · Score: 5, Funny

      I see your ID isn't a coincidence.

    3. Re:Alright!! by argent · · Score: 1, Interesting

      C++ allows for much better code

      Maybe, it simplifies the work of building an OO design, but C++ also allows Heaven and Hell and all the worlds between. Good native C OO code can be just as good as C++, but I find it hard to believe that anyone could have constructed the Escher cathedral that is Mozilla with mere C.

      I might also protest about the purity of Linux' precious bodily fluids. But when people have embedded Perl in the Linux kernel (or did I hallucinate that one?) and a C compiler in the bootloader, any such declaration must of necessity be accompanied by hoots of hysterical laughter from all right minded slashdotters.

    4. Re:Alright!! by Bloater · · Score: 4, Informative

      I think that deserved +1 Funny.

      Although the idea that C++ compiled object code is bloated is incorrect. It's normally either due to inexperience with the language or due to a poor compiler implementation. Part of the problem is that on old compilers, template instatiations were actually included once for every object file that refered to one. More recent compilers can identify and remove duplicates at link time, or can save templates in a separate file and link it in at the end of the build. (For some templates, though, you can actually be better off with one in each file if each file uses inline member functions, and each uses a different one).

      Sure C++ has it's faults, but bloatedness is not one of them - although a standard library may be bloated, but that's not an issue for the kernel.

    5. Re:Alright!! by yanestra · · Score: 1, Interesting
      Why ever not? C++ allows for much better code, you just need a compiler that's up to the task, and runtime ABI that is predictable. Granted, standard C++ may not be appropriate, but with some features disallowed, it is ideal (better than C).
      Because C++ makes your program less deterministic.
      By looking at a piece of code, you can't say what happens where if you use C++.
      During every single instruction, an (unexpected?) exception might take place, and every single instruction might be changed from what the author has intended (and tested) when somebody changed the definitions of what those methods were inherited from.
    6. Re:Alright!! by Bloater · · Score: 3, Insightful

      That's why you have policy. Seriously, what if the locking order for a set of variables changes in C code? Non-deterministic behaviour.

      Any language only goes so far, the thing that determines whether a software development project succeeds or not is policy and attitude.

      For example, you can prevent changes in the apparent behaviour of the language by prohibiting operator overloading, template specialisation, and implicit constructors. Oh yeah, banning macros, which you also have the problem with in C.

      And you don't have to worry about unexpected exceptions, because even if you didn't try-catch, the compiler cleans up *all* your objects in *every* case and tells the function that called you that you failed, and "here's why". The only reason you need to know about exceptions being thrown is to clean up resources and data-structures - and that is done in the destructors for auto class variables, so no problem there.

    7. Re:Alright!! by strider44 · · Score: 2, Funny

      mmm, C++ is way too bloated - the binary code that it produces is horrible. In fact, when you think about it, not even C gives the best possible optimised code - you're wasting a whole 0.001% optimization! They should go backwards, not forwards! They should go for the best possible optimization - Assembly all the way! Just think about the extra microseconds saved - it's a linux hacker's wet dream!

    8. Re:Alright!! by Anonymous Coward · · Score: 0

      Fuck C++ in the kernel.

      Thank you.

    9. Re:Alright!! by Anonymous Coward · · Score: 0

      C++ is more than OO. There are things like RAII that allow you to make the compiler do all your bookkeeping, instead of having to remember it all.

      I might also protest about the purity of Linux' precious bodily fluids.

      Yes, keep the kernel floride free.

    10. Re:Alright!! by Anonymous Coward · · Score: 0

      I think you're either trolling or you don't know what you're talking about. You can't have unexpected exceptions in C++ (except without a compiler extension). All exceptions in standard C++ are ones that occur because of a throw statement. Hardware exceptions like signalling NaNs, trapped integer representations, overflow/underflow, stack overflow, bad memory read/writes, etc. are handled exactly the same way as they are in C so C++ is just about as deterministic as C code in that regard.

      Just because you have exceptions in your language doesn't make it less deterministic if you don't use them (mozilla and QT are large C++ projects that do not use any code that throws exceptions at all). Remember, C has setjmp/longjmp and signals which is less yieldy than C++ exceptions.

    11. Re:Alright!! by orst_sw_engr · · Score: 2, Interesting

      Have you ever debugged at the kernel (protected) level?

      C++ is best avoided at the kernel because of implicate nature of the language. Bugs are harder to find in C++. When an exception occurs, the whole machine must rebooted.

      If you want try this for yourself, just take any amount of code you are working with and every time an exception occurs restart your computer and wait. See how much work you get done.

      Also, while at the kernel mode you must be aware of the whole machine's state including IRQ level, virtual memory, entry context, what IRQs can preempt, and a slough of other details. In user mode you can rely of the state of the machine being fairly stable. However, I would agree that large multi-tiered have many network states that make user mode programming complicated. I have worked in these environments as well.

      Further, you still can write object-orientated code in C if necessary. It just requires the C programmer to manually manipulate the v-table which they create themselves. I have done this. You can do it in ASM too with structs of jump tables.

      Someday C++ will make it into kernel programming, but I think it would be start in a micro-kernel, which is easier to debug.

    12. Re:Alright!! by orst_sw_engr · · Score: 2, Insightful

      I don't mean to be too hard, but I feel I have to bring a different prospective.

      Macros in C are used for readability and easily debugged. All you have to do is grep for the #define.

      The locking order in C code? THERE IS NO LOCKING ORDER. You have to explicitly mange these aspects in C and anyone can immediately determine it from looking at the code.

      Your explanation of memory management within the kernel is at best naive. What if the code is called within a context that is higher (or the same) IRQ level as the VM pager? There is no heap! There is only a small amount of non-paged memory that had to allocated ahead of time and the very limited kernel stack.

      And your notion of what an exception is (in both user mode and kernel mode) is beyond naive. Exceptions can happen for any number of reasons. Simply catching them and cleaning up may not be sufficient. Maintaining an understood state for the rest of the system is the proper course of action. In a network application it may require invalidating a cache to avoid data corruption, or in a kernel routine setting up an I/O request to be handled at a lower IRQ level. Do you propose having all this in the destructor?

      Sure you can randomly clean up everything you can think of, return to the caller, and hope everything works, but in the kernel an unknown exception results in an inevitable reboot. And on a clustered network -- data loss.

    13. Re:Alright!! by dooglio · · Score: 1
      I admit, I've never written kernel level code. I've done mostly GUI stuff, and I think C++'s object orientedness lends itself well to a GUI paradigm.

      I learned coding in straight C first, and then later taught myself C++ when it started becoming popular. When I got into GUI development, I discovered that you have to, < So, I would imagine, to allow C++ into the kernel would take a big rewrite to allow for it.

    14. Re:Alright!! by orst_sw_engr · · Score: 1

      I totaly agree with you.

      Especially the use of deterministic? Exception handling is very deterministic. Sometimes it maybe a little to tricky to follow.

      As a matter of fact, even the Windows kernel (and compiler) makes extensive use of structured exception handling. Not only does it have a try and catch block (they call it try & except), but a finally block which is essentially a nested out of order execution after all the handlers have been evaluated. Also the exception handler has the ability to continue execution right where the exception was raised like nothing happened.

    15. Re:Alright!! by Bloater · · Score: 3, Interesting

      Yes, I have debugged at the kernel level, written a boot loader, switched to protected mode inluding operating the GDT, IDT, page tables, vga registers. written a VGA terminal, etc... I am familiar with x86 assembler, C and C++.

      When an exception occurs, it must be caught and handled correctly (or propagated if that is appropriate) - just the same as a C error code returned from a function, so no loss there. As an advantage, an exception follows a distinct error path back up the stack frames so an error code is *never* treated like a value - which can spell a horrible death for both your uptime and data.

      Within a syscall in process context, an uncaught exception will propagate up and up and up until it reaches a catchall at the syscall entrypoint, which can return an error to user-space without *any* harm to the kernel (provided the code is structured not to leave inconsistent state - but you have precisely the same issue in C, and C++ exceptions actually make it *easy* to clean up the state as you fall back through the stack frames).

      Within a hardirq handler, the interrupt vector points to a similar catchall - the issue here is that timer interrupts (until the scheduler becomes tickless) and interrupts notifying of readiness by hardware can be missed, but only if you haven't handed off to a softirq or queued data for processing by a kernel thread. The C symptom of incorrect code is again different - the code carries on with incorrect data and balls' everything up in C, in C++ it gives up and leaves everything in a good state - unless the hardware *requires* servicing, but then your code simply has to be correct whatever language it is.

      Within a kernel thread, the entry function will have a catchall that kills the thread and a monitor waiting for it's death can see it, log it and restart. Or you can write the code correctly as you have to with the C version (because if you write incorrect C code, the code carries on with bad data and balls' everything up).

      So C++ can actually make the system *more* robust, not less. In particular - the raising of an exception does not kill the system except for rare cases where the calling function *also* doesn't bother to catch errors - and then some bug in a destructor prevents returning the state to how it was ! Which will kill your system in C too (or worse - corrupt data which is *far* less likely with exceptions).

      C code has the added policy issue of clearing up resources on error. Since you often have at least two return paths, resource release code *must* be put into each and synchronised. This is precisely what exceptions do best - automatically nonetheless.

    16. Re:Alright!! by maxwell+demon · · Score: 3, Insightful
      Because C++ makes your program less deterministic.
      C++ programs are as deterministic as any other computer program. Unless you have undefined behaviour (line uninitialized variables or dereferencing dead pointers), a C++ program always produces the same output for the same input.
      By looking at a piece of code, you can't say what happens where if you use C++.
      Yes, you can. Of course you must know the definitions of the entities used in your code, but that is true in C as well. Example:
      foo (*bar) (baz);
      Now, does this line
      • define bar to be a pointer to function taking type baz and returning type foo, or
      • call function foo on the value you get by dereferencing pointer bar, and then call the function to which the pointer to function returned by foo points on the value baz, or maybe
      • expand the macro foo (*bar), which results in a construct which followed by (baz); gives some valid C code which could do just anything?
      Note that even without macros, there are already two possibilities. Now, C++ adds mode possibilities, but that's only a quantitative change, not a qualitative one.
      During every single instruction, an (unexpected?) exception might take place,
      Nonsense. Exceptions can only take place at well defined places (the only way to get an exception is to write "throw xy", either directly or through called code). And if that exception is unexpected, then either the used library is buggy, or badly documented, or you just didn't read the documentation.
      and every single instruction might be changed from what the author has intended (and tested) when somebody changed the definitions of what those methods were inherited from.

      That's wrong, too. There is no way you can change the meaning of e.g. int i=3+4; in C++. Of course there are things where you can change the meaning, but that's no different to the following statement about C: "every function call might be changed from what the author has intended (and tested) when somebody changed the definitions of what that function calls."

      Clearly if anything you inherit from changes semantics, then this is a break of interface, just as changing semantics of a function is a break of interface. You shouldn't be surprised that if you use a library which does not conform to the specification your program expects then your program breaks. That's independent from language, coding style, programming paradigm, it's even independent from programming (e.g. if you think "moron" is something positive, then telling someone a moron will surely not have the effect you expected).

      --
      The Tao of math: The numbers you can count are not the real numbers.
    17. Re:Alright!! by Bloater · · Score: 4, Interesting

      Macros are not always easily debugged, identifiers can be replaced wholesale by #defining it, but not *before* the define, so the header that defines a static variable parses fine, then you include a header from another part of the kernel, then you use the identifer. In the next version of the kernel somebody #defines the identifier you are using within the second header.

      This breaks, and is very hard to debug by code inspection or by kdb. It is resolved by policy ensuring that the namespace for symbols/types/structs doesn't meet with the namespace for preprocessor macro's except for possibly a few agreed core macro's.

      And it is similar policy that keeps C++ code safe.

      Regarding your comment on the locking order. You make my point very well, in C, you have to manage locking order *at*every*call*point*, in C++ you can manage it where the locks are defined. So you make rules like lock A cannot be taken if lock B is already held. In C you have to make this just policy, in C++ you can do some neat code for these cases )though I'm not going to think it through now) that, depending on situation will BUG at runtime or even flat out refuse to compile. And to the user at the call point, it's just a lock.

      As to memory management, I didn't explain memory management in the kernel, so I don't understand how I could have explained it naively. There is not just a small amount of non-paged memory allocated ahead of time. Anytime you need to be able to handle an error, you ensure (before the error can occur) that you have memory in which you can store intermediate data in the process of handling the error - otherwise you are dead in the water. Other than that, memory can be allocated within the kernel via a number of means, including kmalloc and the slab allocator. As to IRQ levels, I have an old first year OS and hardware architecture design textbook that discusses them (by a different name - so I could be misunderstanding what you mean), but that is in non-monolithic designs. I am not familiar with whether allocation is permitted in hard IRQ context in Linux or, if it is, by which of the available mechanisms, but if it is not permitted the hardirq *must* have the memory available to handle the error - whether it is C or C++. Throwing an exception in C++ does not require using any memory: in throw SomeException(blah), sizeof SomeException can be 0, and it can store it's information in the preallocated memory for that instance of the IRQ handler (which can of course be an object). If the C++ implementation doesn't allocate memory that it needs for trundling up the stack ahead of time then that is a Quality of Implementation issue, and different exception handling code is required but C++ is still acceptable.

      And my notion of an exception is not naive at all. In well written code, when an exception is caught all objects in the try block are destroyed, and the data they represent goes with them so the destructor *does* whatever else is required for the state and change of state that it stands for. In C you have no choice but to try to remember everything in each error case (or use goto's to the one place - but then that's just like a low-feature exception with no compiler support for enforcing policy). Maintaining an understood state for the system is done by encapsulating things in objects and using destructors to handle keeping everything consistent.

      All cleanup due to error occurs in one or both of two places: The destructors and the catch blocks. Mostly in the destructors. And you don't *randomly* clean up everything you can think of in C++, that's what you do in C. In C++ you rigourously clean up everything, whether you could think of it or not, because the compiler knows it's there. In the kernel an unknown error )whether by exception in C++, or error code in C) *must* be understood or passed on up the call stack until either something knows what to do, or the whole operation is abandoned for better or worse. In C, that is a lot of work and checking everything, in C++ it's virtually guaranteed.

    18. Re:Alright!! by orst_sw_engr · · Score: 2, Interesting

      Well I made two posts and I appreciate your well-written, civil replies. Sorry for using the word naive.

      True, looking at your original post I am not sure where memory management came into play so I will not harp on it too much. I will point out that the pager works at a low interrupt (which makes sense because disk i/o is required and if it was higher it could preempt threads that don't expect memory moved on them). If a higher interrupt is being serviced it will not have access to virtual memory. Memory simply cannot be created at this level. You are right about the guarantee - for exceptions, the stack is easiest to use. You also right about throwing a primitive in C++ -- it uses no memory.

      I agree that SEH (Structured Exception Handling) has its place in the kernel. As a matter of fact, NT has always had this built into its C compiler. (I actually already made reference to this in a post below.) It even has a finally block for cleanup like you are describing (kind of like a destructor). I have found this feature indispensable. So we both agree this is a good feature.

      BUT! I take issue with most other C++ features which I *love* in user mode, but would be a pain to debug in kernel mode. Interestingly I have done some from polymorphism in the kernel by building my own objects with a variant function table. I find this easier to debug while working in the kernel, but in user mode I would never dream of wasting my time doing this myself.

      As far as defines... I guess I have gotten so use to them; they don't bother me. I can track down the symbol.

      When it comes to C++ for me, it is not the system itself. It is the time it takes to debug it. User mode has much better tools for debug C++. Maybe that is the problem.

      You can have the last word. I am done with this subject.

      Oh, I would like to add one thing the system wide catch on NT is the BSOD.

    19. Re:Alright!! by jmv · · Score: 1

      During every single instruction, an (unexpected?) exception might take place, and every single instruction might be changed from what the author has intended (and tested) when somebody changed the definitions of what those methods were inherited from.

      Exceptions are thrown explicitly, not by "every single instruction". So as long as you're not calling throw yourself or calling a function that is allowed to throw, there can be no exceptions.

    20. Re:Alright!! by Anonymous Coward · · Score: 0

      By looking at a piece of code, you can't say what happens where if you use C++.
      During every single instruction, an (unexpected?) exception might take place, and every single instruction might be changed from what the author has intended (and tested) when somebody changed the definitions of what those methods were inherited from.


      By looking at a piece of code, you can't say what happens where if you use C. During (nearly) every single instruction, an (unexpected?) segfault might take place, and every single instruction might be changed from what the author has intended (and tested) when somebody changed the functions it calls - or wrote a macro that totally fucks everything up.

      Programming is unsafe. C++ programming is safer than C programming. And those who give up attainable safety to gain an imperceptible speed advantage deserve neither safety nor speed.

    21. Re:Alright!! by a_hofmann · · Score: 2, Interesting

      You are absolutely correct that the main problems with compiled C++ lie in the current implementations. But this is a pretty theoretical thing to say, as I don't see this getting much better in near future. C++ compilers have only recently reached a level of full standard compliance, and optimization is surely not yet on par with the things possible for C compilers. C++ is a more complicated language which means it is more difficult to optimize for the compiler, and it is probably not ever possible to optimize to a level that can be reached for C or simpler languages.

      As an example, Windows has a modified microkernel architecture and is a (non-pure) object oriented operating system, so by design it would be logical to implement this in an object oriented language. Still it is no coincidence that most parts of it are written in assembler and C - you just cannot afford to waste percentages of performance for critical kernel sections because of the choice of language, which is not avoidable either, no matter how well you use C++ or optimize with the compiler. And unfortunately most kernel sections are pretty performance critical...

      Btw note that I talk about problems occuring when using the full range of C++ features that make it the beautiful language it is... I ofter hear people talking about C++ matching C performance, but when you look under the hood they are basically using C with some syntactic sugar. This is not of much use, as such designs can be (and are) mostly implemented in C in the same fashion either, as e.g. the object orientism of the Windows kernel I spoke of.

    22. Re:Alright!! by apankrat · · Score: 1


      Example:

      foo (*bar) (baz);

      Now, does this line

      * define bar to be a pointer to function taking type baz and returning type foo, or
      * call function foo on the value you get by dereferencing pointer bar, and then call the function to which the pointer to function returned by foo points on the value baz, or maybe
      * expand the macro foo (*bar), which results in a construct which followed by (baz); gives some valid C code which could do just anything?


      * none of the above as it's all cleverly ifdef'd by an inclusion of custom stdio.h :-p

      --
      3.243F6A8885A308D313
    23. Re:Alright!! by AnotherBlackHat · · Score: 1
      ... C++ allows for much better code ...


      Don't they teach you youngin's about turing equivilancy in programmer school?
      A real programmer can write FORTRAN in any language.

      Good code is about thinkin' not writin'

      -- should you believe authority without question?
    24. Re:Alright!! by Bloater · · Score: 1

      I appreciate your civility (which my other "adversary" in this discussion appeared to have some difficulty with to begin with). A great deal of C++ code *is* just C, that is true. It has similar builtin types with similar semantics. But C++ allows objects to have inline member functions, and constructors can be collapsed to almost eliminate the excess copying problem that I have seen mentioned somewhere in this topic. G++ does very well at this, and clean code with encapsulated logic can be compiled to object code *at least* as good as the C version. There is *still* the possibility of excess copying, but only where code is not inlined - I can imagine extensions that might eliminate this, but there is no point discussing them here as they are not available.

      The mechanism by which excessive copying is reduced looks like this (note that I'm not making this the nicest code, as you see A has an excessive member where non-member operator<< should be used - but I wanted the example to just show one thing):

      class A {
      public:
      inline A () : data(0) {};
      inline A(const A& a) : data(a.data) {};

      inline A operator++ () {
      ++data;
      return *this;
      }

      inline void printit () {
      std::cout << data << std::endl;
      }
      private:
      int data;
      };

      void fn(const A thea)
      {
      A locala = A(thea);
      return ++locala;
      }

      int main ()
      {
      A mya = fn(A());
      mya.printit();
      }

      The compiler can (and I think recent g++ *does*) compile main to the equivalent of

      int main ()
      {
      int myadata;
      ++myadata;
      std::cout << myadata << std::endl;
      }

      which is just as fast as the C version (bugs notwithstanding as I haven't checked this code). Even though there is a copy to the argument of the function, a copy to the local variable in the function, and a copy of the return value. For complex examples, the C++ version can actually be noticeably faster than C.

    25. Re:Alright!! by boelthorn · · Score: 1

      You did not point out why C++ is "plain better" than C, at all. I.e. much of multiple platform support is low-level stuff, that will probably not fit into your nice templates.

      Btw, you would have to freeze the C++ ABI or use one version of GCC forever. I cannot count how often the GCC folks broke binary compatibility.

    26. Re:Alright!! by Bloater · · Score: 1

      I agree with you for sure. The reason I think C++ is plain better than C is that you can think through you policy and encode most of it in the classes and templates that the other parts of your code will use. That means there is less thinking required for the same quality - or alternatively do the same thinking and get better quality.

      The importance of policy in any large development project cannot be overstated.

      Although I now realise I may have completely missed the irony in your post (or was it satire, hm, yes, I think it was satire).

    27. Re:Alright!! by Bloater · · Score: 1

      I have pointed out why I think C++ is better than C in other posts in this thread, so I won't repeat it here.

      Your comment on ABI stability in g++ is fair, but I would expect if g++ were used by the kernel, the g++ sources would evolve to provide hooks for standalone operation where the sources being compiled could provide implementation of the ABI.

      As to templates not being appropriate for low-level stuff, that is exactly what they are appropriate for. You can use template specialisation to cleanly replace conditional #defines. They check your code better, and can't screw up as much stuff if misused and the compiler can check many types of misuse. They also allow for much better code tailoring for different platforms, which can reduce object code size, and increase performance. And all that is done at compile time, so no problem with low-level issues there.

    28. Re:Alright!! by AnotherBlackHat · · Score: 1

      Which language is better for telling stories; French, German, English, or Greek?

    29. Re:Alright!! by Bloater · · Score: 1

      the only significant difference between C and C++ that requires different code is that a void* is implicitly converted to any other type of pointer in C, so malloc actually becomes relatively safe.

      In C++ new does the same job, ensuring safety all the while (although you *can* still force bad code on the compiler if you really try). So while C++ is not a strict superset of C, it can easily express any code structure from C in an almost identical manner. The natural languages you give are not even very closely related. A more applicable example would be Oxford English versus Yorkshire Downs English. Yorkshire Downs English includes most of Oxford English, but has a few extra constructs (thou, thee, thy, thine to name a few) that allows the story teller to describe the relationships between people much more succinctly and possibly with greater dramatic effect - but can still tell any story as using Oxford English with almost identical effect, effort, and structure.

      For story telling, Yorkshire Downs English is better than Oxford English (IMHO)

    30. Re:Alright!! by colmore · · Score: 1

      It's just plain better than C eh?

      I've definitely found C++ programs to be larger and slower running than their equivalents in C by a noticable degree. When you're dealing with something as fundamental as the kernel this is a problem

      If they started implementing a C++ kernel, there would be a crowd who would insist on maintaining the C kernel for performance reasons. The two codebases would very quickly diverge and Linux would be split in half.

      I don't think template functions and objects and slightly easier error handling are worth that.

      My suspicion is that you are a student. I'm not a professional either, but I'm aware that there are good reasons that C++ is used sparingly and only on certain types of projects out in the real world. Just because it makes some programmer's lives easier doesn't mean it results in a better product.

      --
      In Capitalist America, bank robs you!
    31. Re:Alright!! by Bloater · · Score: 1

      No, I am not a student, I completed my degree over two years ago, and there is no reason for C++ code to be slower than C code except for hurried code and not understanding how to make C++ work for you (how many people bother to write const member functions, etc).

      It almost entirely comes down to implementation. The fact that you can translate C almost one-to-one to C++ gives you a place to start with *no* overhead other than name mangled symbols to support overloading (and these can be wrapped for the module API and then stripped). Then add templates and then start using OO. So far very little change other than performace improvements. Then the big change is exceptions. These cause larger binaries normally because the implementation of exceptions usually gives you a short fast path with an extended error path. This is the only size overhead I know of after dealing with the symbols and it is not a lot due to savings in the fast path.

      As a test, I just compiled a 250 line C file as C++ after making the necessary adjustments to make it compile. I compiled it as g++ -xc++ -O3 -s -oprogcascc prog.c, and gcc -std=c99 -O3 -s -oprogc prog.c

      here are the results:
      -rwxr-xr-x 1 user group 7200 2004-10-28 23:11 progcascc
      -rwxr-xr-x 1 user group 7364 2004-10-28 23:12 progc

      Now tell me about bloat. Any bloat with C++ code is all just symbols and exception handling or code designed with multiple versions of the same code for different cases to push higher performance. Not to mention that different exception handling code can leave the code size the same, or even *less* depending on the ABI. As I said in another post, g++ is open source and there is no reason why, when faced with being useful for the kernel, that it can't end up providing hooks for non-hosted ABI customisation. Sure it could take a couple of years, but that's no reason not to do it.

  6. Yay! by stonecypher · · Score: 3, Insightful

    It's about fucking time. Now maybe we're on the path to a bullet for killing those shallow arguments about C++ somehow being majorly slower than C, as opposed to people just not knowing the costs of C++ features.

    --
    StoneCypher is Full of BS
    1. Re:Yay! by Anonymous Coward · · Score: 0

      And just not knowing the costs of C++ development!

    2. Re:Yay! by apankrat · · Score: 5, Informative

      It's not the slowliness, it's the obscuirty and the lack of control over the binary code size it introduces. Something as simple as 'a == b' may easily add few KB to the kernel.

      If you think it's OK, you obviously haven't been involved in kernel or embedded development. If you say one should be careful what features of C++ he uses and not to use this and that, I say one should learn proper C skills instead.

      --
      3.243F6A8885A308D313
    3. Re:Yay! by Lally+Singh · · Score: 5, Insightful

      Embedded dev is now often C++ based. It's all about making sure you have devs who have a clue.

      Anyone writing a == b should notice that a & b aren't primitive types.

      --
      Care about electronic freedom? Consider donating to the EFF!
    4. Re:Yay! by Anonymous Coward · · Score: 0

      Please describe a case where in C++, 'a == b' would add to the size of the code. Presumably, you are referring to overloading the == operator, in which case the equivalent C would require a function that does the same thing, taking up the same size.

    5. Re:Yay! by SpaceLifeForm · · Score: 2, Insightful
      It doesn't matter if the developers have a clue. Linus has repeatedly said no.

      Go fork your own kernel then. Good luck.

      --
      You are being MICROattacked, from various angles, in a SOFT manner.
    6. Re:Yay! by oscrmyer · · Score: 0

      You are right on the ball with this. The Linux kernal is already getting too large. Lets keep is small. Size does matter! Hello

    7. Re:Yay! by Frizzle+Fry · · Score: 3, Insightful
      Something as simple as 'a == b' may easily add few KB to the kernel.

      Only if you've overloaded operator==. But in that case, this is just a function call. A function call in C could just as easily add a few KB. The only difference between the languages here is that C++ gives you the "syntactic sugar" option of creating functions with the same names as operators. You can choose not to do that if you perfer and just use a regular function name, as in C. In no way does the ability to create a function named "==" instead of "Equals" show any more "lack of control" over code size than in C (exceptions might have been a better example).
      --
      I'd rather be lucky than good.
    8. Re:Yay! by apankrat · · Score: 2, Funny

      Assuming you are looking at integer_t type, is it primitive ?
      Made you look in header :-p

      Agreed about developers though, however the number of
      those who have a clue is drastically lower than those
      who think they have a clue. Everyone's a freaking C++
      senior these days.

      --
      3.243F6A8885A308D313
    9. Re:Yay! by myg · · Score: 5, Informative

      I'm an embedded developer. I've done some projects as C only and some as C++. With proper discipline C++ can actually generate smaller, more compact code than straight C. But getting the infrastructure done is a bit harder.

      In fact, eCos, a very nice (GPL) embedded operating system has its kernel written in C++. eCos performs well and is cleaner than a competing straight C RTOS which has to build its object system by hand (VxWorks' WIND kernel).

      The real difficulty in using C++ for embedded development comes from the toolchains themselvs. Frequently new processor architectures don't have very functional C++ back ends but C is somewhat stable.

      In fact, I worked on porting some C++ TV middleware to a specialized "media DSP processor." The GCC back-end for C was rock solid but C++ constructs would give me constant ICEs.

      C++ does fix some dumb things in C, but when it comes to shooting yourself in the foot, C++ is like an AK-47 while C is more like a .38 special.

    10. Re:Yay! by Bloater · · Score: 1

      if a == b adds a few kb to the kernel, its because the implementation of operator== for the two types has been inlined. either the compiler did it because it thought it would be good (which you can disable), or it did it because the programmer told it to - which is correct.

      the alternative with C is to do compare_atype_btype (&a, &b); and that can suffer from the same problems.

    11. Re:Yay! by Martin+Blank · · Score: 2, Funny

      C++ does fix some dumb things in C, but when it comes to shooting yourself in the foot, C++ is like an AK-47 while C is more like a .38 special.

      This should be good news to the NRA's development division...

      --
      You can never go home again... but I guess you can shop there.
    12. Re:Yay! by hackrobat · · Score: 1
      a & b aren't primitive types

      Have you overloaded the & operator then?

      :)

    13. Re:Yay! by Anonymous Coward · · Score: 1, Insightful

      Something as simple as 'a == b' may easily add few KB to the kernel.

      And it can do the same in plain ANSI C, for example when "a" is defined as a macro.

      If you say one should be careful what features of C++ he uses and not to use this and that, I say one should learn proper C skills instead.

      Maybe you should just use proper C++ skills; it's not that hard, and in the end, it results in better code.

    14. Re:Yay! by Anonymous Coward · · Score: 0

      Something as simple as 'a == b' may easily add few KB to the kernel.

      This is an amazingly uninformed statement. Let me guess -- you don't really _know_ C++, you just read C news groups and follow the party line, right?

      Tell ya what, we'll let you continue to use your "proper C skills", and the rest of us will move forward. Deal?

    15. Re:Yay! by Anonymous Coward · · Score: 0

      but isn't that the whole point of operator overloading? you don't care what types they are, you just wanna know if they're equal.

    16. Re:Yay! by bobv-pillars-net · · Score: 4, Insightful
      Go fork your own kernel then. Good luck.

      Unless I misunderstood when I RTFA, that is exactly what the authors intend to do. And I, too, would like to wish them "Good luck." Linus obviously believes that C++ in the kernel is undesirable, but we'll never find out for sure until somebody like these people have the guts to actually try it, and the persistence to maintain a current patchset (or fork) long enough for the idea to catch on.

      --
      The Web is like Usenet, but
      the elephants are untrained.
    17. Re:Yay! by Anonymous Coward · · Score: 0

      Well mabye if there weren't as many opnions about cost and a good definitive manual on function costing then perhaps all those Visual C++ devlopers out there might learn to write optimized code?

    18. Re:Yay! by Doppler00 · · Score: 1

      Something as simple as 'a == b' may easily add few KB to the kernel.

      Isn't this more of a flaw in whatever C++ compiler is being used? I would think that a fully optimized compiler would be efficient enough for you to balance size/speed correctly.

      If anything, C++ as a language is superior to C as far as being able to better describe whatever algorithm you are using. It's just a matter of efficiently converting that higher level of abstraction into efficient op codes.

    19. Re:Yay! by Anonymous Coward · · Score: 0

      C++ works quite well at the embedded or kernel level in my experience. You need developers who actually know the language though. I think that is the biggest challenge involved.

    20. Re:Yay! by Erik+Hensema · · Score: 1
      It doesn't matter if the developers have a clue. Linus has repeatedly said no.

      This argument can also be applied to support for multiple processor architectures in the kernel. Linus said it would probably never happen. He said the kernel would only run on i386 compatible processors. Today Linux runs on about any processor you can think of.

      Linus can be persuaded by good arguments. His opinions aren't static.

      --

      This is your sig. There are thousands more, but this one is yours.

    21. Re:Yay! by stonecypher · · Score: 1

      If you think it's OK, you obviously haven't been involved in kernel or embedded development.

      Actually, I've been doing embedded development for a living for almost six years. With proper care, C++ generates smaller binaries with smaller memory footprints than C, thanks to userland control of pooling, policies, and linking-discardable specializable libraries.

      If you say one should be careful what features of C++ he uses and not to use this and that, I say one should learn proper C skills instead.

      That's a total straw man. What I said was that the costs of C++ development were misunderstood. That has little to do with your knowledge of C, save where the two languages overlap, and where they overlap that's a tautological non-distinction.

      Back under your rock, savage.

      --
      StoneCypher is Full of BS
    22. Re:Yay! by Hockney+Twang · · Score: 1

      Did you know that the round fired by an AK-47 is pretty much a rifle length .38? So the only significant way that an AK is worse is if your selector switch is set to auto and you've got a really steady hand.

      There are differences, though. A .38 is likely to fire a more blunted round, with a full-lead projectile, and will molt(break and spread, causing more damage) when it strikes your body. The AK-47 is commonly loaded with metal-jacketed rounds, which penetrate further, but don't break down and spread on impact. So the logical conclusion is that you might be a lot better off shooting your foot with an AK.

    23. Re:Yay! by Taladar · · Score: 1

      The problem with OOP is that even though there are good arguments for it (and against it) most OOP-Zealots just use things like "Can't you see OOP is clearly superior" and call those arguments.

    24. Re:Yay! by apankrat · · Score: 1

      > If you think it's OK, you obviously haven't been involved in kernel or embedded development.

      Actually, I've been doing embedded development for a living for almost six years. With proper care, C++ generates smaller binaries with smaller memory footprints than C, thanks to userland control of pooling, policies, and linking-discardable specializable libraries.


      I didn't mean to sound it personal. It's an ESL thing, no need to be defensive :)

      However the point I was trying to make across was that since C++ does a lot for programmer behind the scenes, it takes more seasoned developer to fully realize all effects of these freebies on the binary output. That's the 'proper care' you are referring to.

      > If you say one should be careful what features of C++ he uses and not to use this and that, I say one should learn proper C skills instead.

      That's a total straw man. What I said was that the costs of C++ development were misunderstood.


      You are forgetting one fairly major cost associated with C++ development - the cost of training and management. From my experience (doing a lot of interviewing lately) if you compare an average C++ and C developers, former would inevitably come out much more overconfident in his skills. Even cocky. And that's outweights all benefits of C++, because it's hard to make a dozen of C++ guys establish common programming principles. That was my second original point - C projects are both easier to manage and are easier to participate in.

      Otherwise I'm fine with C++. I'm using it myself on a regular basis. It's just that it's not suitable for Linux kernel development for a number of reasons, that's it.

      --
      3.243F6A8885A308D313
    25. Re:Yay! by myg · · Score: 1
      Actually my .38 special rounds are more like 9mms. The cartridge seems to have quite a bit less powder than my AK-47 rounds.

      I must say I don't plan on experimenting with my foot so for now we don't have conclusive data.

      I guess I shouldn't use the AK-47 in a C++ analogy. While I use C++ it is a very complex and difficult to master language while the AK-47 is quite elegant and simple.

    26. Re:Yay! by Leimy · · Score: 1

      Actually it might be a bit more than a function call...

      If operator == is defined outside a class defintion either the right or the left hand side of == could have an implicit conversion performed if there is a single argument, non-explicit-labelled, constructor to go from the type on the left to the type on the right or the right to the left.

      Truth is by looking at a line of code you have to know a lot more about the types involved, how they are defined, and other stuff to know what's going on.

      No good C++ programmer will tell you that it's easier to account for the impact of a line of C++ vs a line of C.

      Don't get me wrong either. C++ kernels can exist and can be VERY fast. Check out L4 Pistachio if you don't believe me. It's also highly cross platform compatible [works on many systems].

      They have wisely restricted themselves to a subset of features of the C++ language but have done a great job using the language without going nuts on features. I think it all comes down to discipline.

      If I had it my way you wouldn't write kernels in any C-like language at all. I think C is the root of buffer overruns and other security problems. More rigorously type checked languages like Ada95 or even some functional langs like Haskell would make ideal languages for a kernel if they generate good enough code :). I think Pre-Scheme developers would agree with me.

      In the meantime people can look at safe C dialects like Cyclone and get similar benefits.

      Linus Torvalds has said he's been working on a type checking lint tool for his kernel. Good on him, I say :). That's exactly the right direction for the system to go. I don't think he'd be against a language with stronger typing either if he could get similar guarantees for code generation as C. It almost always comes down to implementation details [of the language].

    27. Re:Yay! by pyrrho · · Score: 1

      but C++ isn't an OOP language.

      it's a language with OOP idioms available.

      bit difference, just ask any C++ hater of the OOP Purist School.

      --

      -pyrrho

    28. Re:Yay! by stonecypher · · Score: 1

      You are forgetting one fairly major cost associated with C++ development - the cost of training and management.

      Which is regularly shown to be far outweighed by the diminished costs of debugging, testing, patching and reimplementation. I'm actually glossing over a lot; you might consider reading some PHB books.

      --
      StoneCypher is Full of BS
  7. What about Java in the kernel? by Anonymous Coward · · Score: 0, Interesting

    n/t

  8. Exceptions are suddenly viable? by gbjbaanb · · Score: 2, Insightful

    oh dear, again someone who doesnt; understand that exceptiosn are designed never to be thrown. If they were everyday occurrences, then they wouldn't be, well, exceptional.

    Unlike some languages who use exceptions for events that you expect (like End-of-file) and poor programmers who think that because they're there, they must be used all the time, for everything, exceptions are a defensive programming measure to ensure that the things that should never, ever happen, are handled gracefully if they do.

    1. Re:Exceptions are suddenly viable? by 21chrisp · · Score: 1

      True. If an exception is thrown, it's mostly likely a program-halt condition. Which you obviously don't want in a kernel.

    2. Re:Exceptions are suddenly viable? by toggles · · Score: 0

      as opposed to a kernel panic?

    3. Re:Exceptions are suddenly viable? by 21chrisp · · Score: 1

      Similar, but an exception allows for a gracefull exit before the *crash* occurs. This is useful for apps because it will save data and exit normally (without memory leaks) where a true crash couldn't avoid this. But at the kernel level both will result in the same thing (at least I would think). I suppose a kernel exception might be able to go as far as shut down your computer rather than lock it..

    4. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      If it gets as far as a sync(), I'm happy.

      On Linux, sync() seems to wait until the buffers are flushed.

    5. Re:Exceptions are suddenly viable? by slashrogue · · Score: 1

      That may be true in a lot of cases, but in the operating system? You can't guarantee ANYTHING is what you want it to be.

    6. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 2, Informative

      exceptions are a great way to structure your error handling.
      they're an in-language mechanism similar to signals, only that they don't have the brain-deadedness of them.

      Hell, just having smart pointers whose destructors are properly called on the stack unwind is enough.

      --
      Care about electronic freedom? Consider donating to the EFF!
    7. Re:Exceptions are suddenly viable? by BCoates · · Score: 2, Informative

      I think that's a bit backwards; ordinary user applications can just terminate ungracefully, and the kernel will clean up after them (close all open files, free memory, etc) if a section of kernel code runs into a problem, it has to roll back everything to a sane state before returning to the caller if there's going to be any hope for the entire kernel to keep going (without leaking). I believe right now the linux kernel mostly does this with an elaborate system of gotos and return value checking that's pretty much exactly what C++ stack-unwinding does, just by hand.

    8. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 4, Informative

      Nope. It's a condition that the throwing code couldn't handle. Someone else can handle it.

      Classic example: a method calls another that calls another that calls openfile() for a temp file, which fails. the lower two methods don't care, and the toplevel one can give the user a proper error message and clean up.

      People wonder why software is so hard to test, does so poorly on error handling, yet complain whenever we add mechanisms to languages to help.

      --
      Care about electronic freedom? Consider donating to the EFF!
    9. Re:Exceptions are suddenly viable? by cout · · Score: 4, Informative

      Oh dear. Another person who thinks that exceptions should never be thrown.

      If exceptions were never meant to be thrown, they wouldn't be in the language. Exceptions are an abstraction for dealing with exceptional conditions -- conditions that do not normally occur, but can occur. At the expense of some additional complexity, they make error checking a little simpler and less bug-prone. When (not if -- assuming you are a believer in Murphy's law) those exceptional conditions occur, your program better be able to handle them correctly.

      You are right that some people do use exceptions when not appropriate. Exceptions are (generally) not appropriate for exiting loops, for example. But they are more than appropriate for out of memory conditions, out of disk space conditions, etc.

      The reason they are not viable performance-wise is not because they are too expensive to throw; it is because they are too expensive when they are never thrown at all. There's generally a 5-10% performance hit just from having code that might possibly throw an exception, depending on your compiler's implementation. The numbers on the netlab page are for throwing exceptions, unfortunately; I would be interested in seeing if they got a performance benefit when exceptions are not thrown. Guess I'll have to dig to find a copy of the paper.

    10. Re:Exceptions are suddenly viable? by AuMatar · · Score: 0

      I'd have to disagree. Exceptions move the error handling away from the code causing the error, making it difficult to tell exactly what call caused the error, and breaking up the logical flow of the program. The C code

      error=do_foo()
      if(error) //handle error and return if error unfixable
      do_next step

      makes it easy to tell what exactly caused the error. It also makes logical sense- an error occurs, you fix it immediately, life goes on. The exception based code:

      try
      do_foo()
      do_next_foo()
      do_foo3()//continue on here for 10 lines
      catch a //handle a
      catch b //handle b ...

      This is horrible. You don't know what had an error. You also lose the flow of the code- the physical separation makes it much more difficult to understand. The ONLY advantage of this is not needing to return an error code, allowing do_foo to return a value. It would have been a far better idea to just let C++ allow multiple return values from a function instead (so a function could be declared to return 2 ints, for example). This would have been a very useful feature. Instead we get this mistake called exceptions.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    11. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      Exceptions are useful for libraries where the problem can't be dealt with by the library code. You document the exceptions that can be thrown by a class and so the app can handle them.

    12. Re:Exceptions are suddenly viable? by Waffle+Iron · · Score: 1, Troll
      oh dear, again someone who doesnt; understand that exceptiosn are designed never to be thrown.

      I disagree. Exceptions are appropriate in many cases for conditions like "file not found" errors. These can be expected to happen in the ordinary operation of the program.

      The whole advantage of exceptions is removing the need for complex deeply-nested if (errorcode) statements or error-prone goto exit jumps. It also removes the dilemma of functions returning useful information and an error code at the same time (without exceptions APIs usually provide a messed-up combination of in-band and out-of band information).

      If you never use exceptions, you have to deal with all of that garbage even if the language is prepared to help you. Why not use the feature to clean up your code? Handle errors in a few choice spots where you're prepared to deal with them, not on every alternate line of your app.

    13. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 1

      That's why you don't force the error checking to be scattered and disorganized all over the place; you structure and design it with the rest of the system.

      --
      Care about electronic freedom? Consider donating to the EFF!
    14. Re:Exceptions are suddenly viable? by ElGuapoGolf · · Score: 1


      Well... this seems like a poor example to me. You really should be able to tell what's happening by the exception being thrown. If you see a (forgive me for the java examples) java.io.FileNotFound Exception, you can probably figure it out. And in your do_foo() methods, assuming they throw exceptions, you should build and pass back an exception which contains not only the name of the method in which the error happened, but the stack trace as well.

      Just my .02

    15. Re:Exceptions are suddenly viable? by slashdot.org · · Score: 2, Interesting

      oh dear, again someone who doesnt; understand that exceptiosn are designed never to be thrown.

      It's ridiculous that this comment is modded up to +5 Insightful.

      Would you care to back up this claim with something tangible?

      Of course the word 'never' is totally inappropriate since by definition exceptions _are_ designed to be thrown.

      The only valid thing in your comment is that certain programmers over-use exceptions. Then again, certain programmers also do stuff like #define forever for(;;). That to me is over-using #define. So should we rip the pre-processor out of the compiler because certain programmers use #define in a way that you don't fancy?

      Exceptions are extremely useful to write clean code with proper error handling. The truth is that because handing error conditions with return values is cumbersome and ugly, people often just don't implement error handling. Great.

      If they were everyday occurrences, then they wouldn't be, well, exceptional.

      I think it's perfectly normal and acceptable to have an exception be an everyday occurrence. There's nothing magical about exceptions that would justify saying that they should never be used. Sure, throwing an exception is a lot of overhead. So TF what? If you only do it in exceptional situations...

      To me the word 'exception' means to me, anything that happens that's not in the normal code path. The standard software flow should not use exceptions, but anything else is, well, exceptional.

    16. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      Nope. Exception mechanism is a very convenient tool for program flow control. If you have ever tried to write a piece of code containing a few dozen functions calling each other and allowing you to unwind the stack manually on a certain condition, you should know it's a real pain in the ass.

    17. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      understand that exceptiosn are designed never to be thrown

      I disagree. Exceptions should be thrown on errors AND anything that is not expected to happen. While it may be bad to rely on them for flow control (where some programmers just don't understand), they are extremely useful for problems that occur on a regular basis (someone mentioned unpluging devices unexpectedly, but my ideal condition is termination of a network connection unexpectedly.. but I digress)
      The reason exceptions are hardly seen in languages like C++ is that try/catch blocks are damn slow... meh

    18. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 2, Informative

      if it matters which part of the code had the error, then use separate try blocks for each part. In real life, most exception handling code DOESN'T care which function called it, or can tell from the exception type. As we've got more expressiveness than the value for ERRNO, we can do that here.

      --
      Care about electronic freedom? Consider donating to the EFF!
    19. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      Have you _really_ tried to write the code like this, dude? When error handling is 2/3 of your code, and the only way of error handling you need is basically aborting a certain operation?

      Yes, you lose the flow of the code, but that's exactly what you want. And it is done without all this cumbersome scaffolding.

      And no, you know what had an error. This is exactly what the exception object contains. At least when the exceptions are used in a sane way. A few macros, and the exception object may even contain the information on the file and line number where the exception happened, if you really need it for debugging.

    20. Re:Exceptions are suddenly viable? by Anonymous+Brave+Guy · · Score: 3, Interesting
      There's generally a 5-10% performance hit just from having code that might possibly throw an exception, depending on your compiler's implementation.

      FWIW, I believe modern compilers now approach the zero-overhead ideal for exceptions when they aren't thrown, and have done for a little time now. Several people directly involved have posted to this effect on the major C++ newsgroups in the past.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    21. Re:Exceptions are suddenly viable? by tshak · · Score: 1

      There's generally a 5-10% performance hit just from having code that might possibly throw an exception, depending on your compiler's implementation.

      Just to be extra clear to avoid potential confusion: This is a true statement for C++, the language in which we are talking about. However, modern languages like Java and C# do not incur this performance penalty. There is still a small penalty for throwing an exception, which doesn't matter because that should only happen in rare (read: exceptional) circumstances.

      --

      There is no longer anything that can be done with computers that is nontrivial and clearly legal. -- Paul Phillips
    22. Re:Exceptions are suddenly viable? by AuMatar · · Score: 1

      Well, I was being general. Yes, you can improve readability with good names- but that goes for both methods

      error=openfile()
      if(error==FILE_NOT_FOUND){ //handle
      } ...

      Yeah, you can have an exception have the name of the function, but thats not as readable as having the error handling code right there. Especially for maintenance coders trying to understand whats happening. Its trying to make the best of a bad situation- trying to bring exceptions up to the usability of error returns.

      It also doesn't help the following case- you read in 4 bytes from a file, then read in a variable number of bytes based on the last read. You get a read exception. Which read failed? Whats the state of all your objects? If you have the code

      num=read(4)
      string=read(num)

      with an exception, you don't know if num is valid or not during the exception. This can be a real problem in less trivial cases than the above. With error codes, you always know.

      I'm a big believer in KISS as applied to languages. Error codes are simple. THey're easy to undestand. You always know the state of the machine at any time. Exceptions are not. The state of some variables may be unknown. It just adds more qestion marks to the equation, makes it more difficult to debug and maintain. Code should be bash them over the head obvious, if there's any question at any point to what the state of the machine should be, its a bug. One of the reasons I like C so much- it is what the computer sees. One instruction followed by another. Nothing to guess at or puzzle over, nothing that could be changed by runtime decisions of what to call. The ultimate in KISS.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    23. Re:Exceptions are suddenly viable? by BCoates · · Score: 3, Insightful
      try
      do_foo()
      do_next_foo()
      do_foo3()//continue on here for 10 lines
      catch a //handle a
      catch b //handle b ...
      Why are you doing this, if you want to handle errors where they happen? Why not:
      try
      do_foo()
      catch a
      // handle a right when it happens
      if (unfixable)
      throw; // rethrow (or throw something else with throw x;)
      try
      do_next_foo()
      catch b
      // handle b right when it happens
      // etc...
      The equivalent of your error-return based code. Of course, in the real world, most exceptions don't need to be caught explictly as the only error-handling code is resource cleanup or rolling-back half-complete operations, for which you aught to be using destructors. That's where exceptions are more useful than just an arcane alternate syntax for doing the same thing.

      You can senselessly dump all your error handling code in the middle of nowhere using return-value error codes, too, if you really want to.
    24. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 1, Insightful

      It looks like you've combined a beautiful "back in my day" rant with a nice redefinition of KISS to "Keep It Stupidly Simple."

      Just because you don't understand the value of something doesn't make it valueless...

    25. Re:Exceptions are suddenly viable? by AuMatar · · Score: 1

      And you can keep thinking that- up until the point where you would really have liked to know which one it is, and you don't have the information at hand. If its for a hard to reproduce corner case, changing that and recompiling is fucking annoying. Not to mention if you do that you lose the one "benefit" exception people claim it gives them- it moves the error handling code back up to the error causing code (although I disagree that this is a benefit).

      --
      I still have more fans than freaks. WTF is wrong with you people?
    26. Re:Exceptions are suddenly viable? by AuMatar · · Score: 1

      I write code like this all the time. Its much more readable than that exception shit. You do not EVER want to lose the flow of the code. You want the code to read just like the processor executes it- 1 line after another. The epitome of radability.

      No, you don't know what had an error most of the time with exceptions. You knwo something had an error, what it was is usually one of a dozen lines. Good luck figuring out which one. It usually involves going through, making each line catch its own exceptions, which eliminates the one "benefit" of exceptions anyway.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    27. Re:Exceptions are suddenly viable? by iamacat · · Score: 1

      Hardly so. The fact that exceptions meticiously execute destructors suggests that the program is expected to recover from the error and perhaps encounter the same error many times so that resource leaks become an issue. Exception handling would be very useful in kernel, to make sure it can run for possibly years without leaking memory and other resources in conditions like network errors in the middle of an NFS operation, full disks and hot-unplugged devices.

    28. Re:Exceptions are suddenly viable? by AuMatar · · Score: 1

      Why am I doing it that way? Because its the one benefit exception people claim it gives them. If you catch after each line it is exactly like error codes. OF course its error codes with wird syntax and passing methods, so why not just use error codes?

      ANd of course for your point that you don't int he real world need to handle errors after each operation- first off you do (not doing so is the #1 cause of bugs in programming), secondly you can put off handling errors until the end with error codes too- just save the error state. SO once again exceptions have no advantages over error codes.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    29. Re:Exceptions are suddenly viable? by Xua · · Score: 1

      Well, some languages now influence those that were traditionally conservative and used to develop things like kernel. There is nothing wrong with exceptions except that their implementation in C++ is a heavy bloat on the code and quite a slowdown on its performance (I saw -fno-exceptions option in most c++ packages that I installed, and it was used for a reason).
      Languages like java which use exceptions heavily are not a panacea, they rely on the same mechanisms only the code is generated by JIT (well C++ requires executing destructors which java doesn't require so maybe java exception handling it lighter only to be overwheited by garbage collection in a different department :) )
      But computing industry evolves. If there is a strong demand for something there is eventually going to be a supply. Hardware vendords aren't blind when they compete against each other and exception handling may evolve into several new processor instructions that will speed up everything first on one platform, then on the rest of them. It is a matter of competition.

    30. Re:Exceptions are suddenly viable? by Bloater · · Score: 1

      > There's generally a 5-10% performance hit just from having code that might possibly throw an exception, depending on your compiler's implementation.

      Indeed, it is *very* dependent on the compiler. since a function that can throw an exception does not indicate error in it's return value, a compiler may not do any check for error (while in C, you must have a conditional branch on most functions... slowwww). C++ can run through assuming everything is fine and no errors can occur, then when an error occurs an exception is thrown, which means the function with the error doesn't follow the return path, but rather jumps elsewhere. The exception code of the implementations runtime, when jumped too like this, gets the details of the exception and the point where it was thrown. it can then look up for that 4KB section of memory (or more, or whatever) for the code that decides what happens next (so each module could have different exception handling routines). Those routines can then run the cleanup routine for the throwing function (ensuring that every resource is freed on every error), find the catch handler for the calling routine and run that - which drops back to just after the try block, so everything can carry on as normal.

      The compiled code then is almost as good as without any errors even being possible - and it is much faster than the equivalent C. The only way, in C, to get that sort of performance is with a little help from longjmp and friends - this is not desirable as the language doesn't help you get get it right.

    31. Re:Exceptions are suddenly viable? by emarkp · · Score: 1
      Which is why exceptions shouldn't simply be used for "exceptional" situations. They should be used when the current scope can't deal with the problem reasonably.

      Exceptions are no silver bullet. Once they're introduced, you need to make sure all your code is at least exception-neutral (techniques like RAII suddenly become very important). The best time to do that is at the initial design--hence introducing exceptions in an existing codebase should be done carefully and conservatively.

      That being said, if done well, exceptions can make code easier to understand, be less error-prone, and can remove a lot of busy work. If done well, mind you.

    32. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0


      "There's generally a 5-10% performance hit just from having code that might possibly throw an exception, depending on your compiler's implementation."

      Just to be even clearer to avoid your confusion: This may be a true statement (I don't know) for C++ compiled by g++, however, modern compilers like VC++7 do have only a very small performance penalty for exceptions when they are not thrown, which is also true of Java and C#. Also not that Java and C# both have other more significant performance penalties.

      And before anyone gets their panties in a twist let me state for the record that Java and C# have advantages over C++ that may well lead you to choose them. But performance isn't one of them.

    33. Re:Exceptions are suddenly viable? by timeOday · · Score: 1
      There's generally a 5-10% performance hit just from having code that might possibly throw an exception, depending on your compiler's implementation.
      Just to be extra clear to avoid potential confusion: This is a true statement for C++, the language in which we are talking about. However, modern languages like Java and C# do not incur this performance penalty.
      What's that supposed to mean? You can't compile Java or C# programs without support for exceptions to see if they will run faster, can you?
    34. Re:Exceptions are suddenly viable? by Peaker · · Score: 1

      The only insight I can read from your message is that maybe exceptions ought to be renamed, so that fools don't create silly rules about when they are to be used.

      Exceptions are a powerful way/tool to return/propagate values on the call stack, and creating arbitrary limitations on them because they are named "exceptions" is silly.

      Using exceptions for non-"exceptional" cases is often a lot more convinient/powerful than having complicated return values.

    35. Re:Exceptions are suddenly viable? by Beatlebum · · Score: 2, Informative

      You're confusing exceptions with assertions. Exceptions can be used to elegantly handle boundary conditions. Assertions flag events that should never happen *if* the code logic is correct. Exceptions stay in both debug and release builds, assertions are not usually compiled into release binaries.

    36. Re:Exceptions are suddenly viable? by arkanes · · Score: 3, Insightful
      It also doesn't help the following case- you read in 4 bytes from a file, then read in a variable number of bytes based on the last read. You get a read exception. Which read failed?

      The whole point of exceptions is that you don't care. If you care about each specific read, you wrap each read in it's own block (the same as error conditions, except that you'd use an if block).

      Whats the state of all your objects?

      This is why object-oriented C++ is so wonderful and Java is so bad - your objects are automagically in the correct state because you allocate and clean up resources in thier destructors. If an object is in scope, it's in a clean state. If it's not in scope, it's not. You can write some really concise, clean, reliable code using this concept - it's where the true power of objects comes into play. In C, you have to manually check EVERY call and clean up EVERY resource - it's very susceptible to programmer error, especially in deeply nested call chains with gotos and whatnot all over the place (like the Linux kernel, for example). In Java, which doesn't have destructors, it's even worse because you've got exceptions with no automatic cleanup, which means you've got to have all sorts of ugly nested try/catch/finally and state management.

      Exceptions are a nice way of dealing with problems, especially nested calls. But combined with destructors, they're a magnificent way of keeping error handling safe.

      People use goto in C because they want a nice exit point in the case of failure. People use exceptions for exactly the same reason - it simplifies error handling. It's true that it's physically seperate from the code, but on the other hand it's within the same block so you've got a visual/indendation indication at least. If you think exceptions are a maintainers nightmare, then you've never tried to fix an error in a function with 40 different exit points, with almost identical cleanup code at every point. A C programmer would use a goto so that there's not so much duplicate code and it's easier to maintain. A C++ programmer would use exceptions and automatic objects to do exactly the same thing, in roughly the same lines of code, with with even less (quite possible 0) duplicate code and greater modularity.

    37. Re:Exceptions are suddenly viable? by arkanes · · Score: 1

      Modern (ie, good) C++ compilers get this penalty down under 1%. Whether or not it applies to Java is a pretty silly question - Java must (and does) assume that any code can throw an exception. The whole Java language and VM is built around that concept. It's more accurate to say that ALL java code suffers that penalty, at the lowest possible level.

    38. Re:Exceptions are suddenly viable? by E_elven · · Score: 1

      So why can't openfile() simply return NULL? Obviously an unsuccessful operation.

      I don't mind exceptions, except when non-fatal ones are thrown by a library. A module should always either A) handle its non-fatal exceptions or B) provide a secondary implementation that uses return values rather than exceptions.

      I've been working on a paradigm where all functions return a Result object which can easily be used as a replacement for a normal return (op() for the parameterized type, C++ scoping automatically destroying the object at the end of scope etc.)

      --
      Marxist evolution is just N generations away!
    39. Re:Exceptions are suddenly viable? by arkanes · · Score: 2, Informative

      Exactly. Here's an example of poor use of exceptions:

      try {
      while (1) {
      read_from_file();
      }
      } catch (EOFException) {
      clean_up_file();
      }

      This is bad because you're using an exception to manage normal program flow. Here's a better use of exceptions:

      try {
      File f("myfile"); //file object manages state
      while (!f.eof()) {
      f.read();
      }
      } catch (FileOpenException) {
      //file object is cleaned up by it's
      //destructor, only thing we need to do is
      //alert user
      }

      This is a simplistic case, because you can just easily do this by checking error codes. It shows it's worth when you have, say, a dozen different files to open. You save a lot of if-checks, a lot of duplicate error handling (alerting the user and returning), and you don't have to worry about manually closing all the files which might be open, preventing resource leaks. If your exception system is properly designed, you don't lose any information, because stuff like the file you were trying to open is preserved with the exception information.

    40. Re:Exceptions are suddenly viable? by dgatwood · · Score: 4, Insightful
      Exceptions have no place in the kernel. Mac OS X uses C++ in its kernel. Two things are notably omitted: multiple inheritance and exceptions. A lot of thought went into that decisiion, and I didn't come in until shortly thereafter, so I mostly know the fallout of that decision, but... it was defininitely the right decision.

      Exceptions in the kernel are inherently a bad idea. An uncaught exception is a kernel panic. By contrast, an unknown error return is still an error, and usually the right thing happens. The risk of allowing exceptions in the kernel far outweighs any possible benefit. That's why nearly every kernel that has ever used C++ at any level has explicitly excluded exceptions. (That and the very nature of exceptions inherently results in worse performance than using error returns. In the kernel, performance is far more important than facilitating programmer laziness. :-)

      It would be wise for the Linux community to learn from other OSes that have tried to do kernel exceptions. Even the Windows kernel developers rejected them as a bad idea. Don't do it. Don't accept any patch that allows it.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    41. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      > Oh dear. Another person who thinks that exceptions should never be thrown.

      He didn't say "never", he said "not normally". As in cases like throwing an exception at EOF. It's guaranteed to happen if you're reading a file all the way to the end -- so it's not exceptional! Attempting to read past EOF in a random-access file or in a nonblocking read on a stream, that's an exception.

      Additionally, there's also overhead in placing numerous checks of every single return value in the code, instead of collecting exception handling in one place.

    42. Re:Exceptions are suddenly viable? by ChadN · · Score: 1

      You are wrong. What you describe is more like an assertion.

      Handling bad user input might be a case where you would use an exception, and bad user input will CERTAINLY occur. Or resource allocation. Or a host of other things outside the programmer's control.

      Good implementations will have a fast path (the common case) and a less fast path (the exceptional case). In many implementation, these can be as fast or faster than predicates (ie. if-then error handling blocks everywhere)

      Exceptions, in C++, are mostly used to ensure proper destruction of objects, even under exceptional circumstances. For that purpose, they are fairly well suited.

      Just as people unfairly attack "goto" in C (which is invaluable for maintaining code readability in the face of difficult error handling), some people attack C++ exceptions. Each has its place in their respective language.

      --
      "It's overkill, of course. But you can never have too much overkill." - Anonymous Slashdot Coward
    43. Re:Exceptions are suddenly viable? by Pete · · Score: 1
      Why am I doing it that way? Because its the one benefit exception people claim it gives them. If you catch after each line it is exactly like error codes. OF course its error codes with wird syntax and passing methods, so why not just use error codes?

      Wow. What a strange response.

      I don't know where you got the idea that "exception people" claim it's a benefit that you can use exceptions in a way that's just as painful/limited as code using a return-error-code style (though even if you do that, they're still not exactly alike - the exception-throwing style still has advantages).

      The major advantage of using exceptions (in my mind, at least) is that there is no need to use special return codes to signal errors. And there is no way to ignore an exception (as a coder can easily just not check a return code). And you can handle an exception at the most appropriate point in the call stack. And your code doesn't have to have a maze of return-code-checking logic after every single bloody might-possibly-return-an-error function call. And you can signal a failure even from a function that doesn't/can't return a value (eg. a constructor). And an exception object can carry arbitrary information along with it. And cute furry animals and small children will trust you. Your gender-of-preference will find you more attractive. You'll need less sleep and earn more money. Colours will seem brighter and the air fresher. Your google searches will work better.

      The candidate you support will still lose the election, but hey, you can't expect everything :-).

      Slightly more seriously, I think you might be suffering from a mild form of the Blub Paradox WRT exceptions (specifically C++ exceptions in this context). You may find it's worth taking another look, because you are missing a lot if you think of exceptions as just a syntactically weird equivalent of return codes.

    44. Re:Exceptions are suddenly viable? by Tony+Hoyle · · Score: 2, Insightful

      I first came across the widespread use of exceptions in COM with ADO code. They really pissed me off - something deep within ADO (usually nothing to do with me) would throw an exception and a random other part of my program would fall over with *no* indication of where the error came from (it didn't help that this was in the VC6 days and the exception handling was nonfunctional - it trashed the stack so you could never recover.. you had just enough time to put up a dialog before your program was doomed).

      I ended up having to rewrite the com_error object so it traced out a message with the location of the actual error... much later on I worked out how to stop it being thrown in the first place & to return the documented error codes.

      That's the real problem with them - unless you have a catch() after nearly every statement it's basically impossible to work out what went wrong - 'File Not Found' - which file? which function? Why, exactly?

      I totally disagree that you mostly don't care where the error was thrown. I *do* care, because I have to fix it. Maybe the end user doesn't care, but even then I want the code to generate an error report that tells me where to look.

    45. Re:Exceptions are suddenly viable? by AuMatar · · Score: 1
      The major advantage of using exceptions (in my mind, at least) is that there is no need to use special return codes to signal errors. And there is no way to ignore an exception (as a coder can easily just not check a return code).


      The first there is somewhat valid, but there's still better ways than exceptions to do so (why do functions still return 1 and only 1 value? It dates back to the idea of a function in math, but its outdated now). The second is dead wrong- to ignore an exception, just catch all exceptions and do nothing. I know a lot of programmers who do just that to get rid of exceptions they can't fix.

      And you can signal a failure even from a function that doesn't/can't return a value (eg. a constructor).


      Thats a bug in constructors, not a valid reason for exceptions.

      And an exception object can carry arbitrary information along with it.


      Return an error structure then, instead of an error value. The extra info isn't usually useful though. You aren't going to be using that info for anything but debugging, and your debugging logs probably have more info.

      I think you're reading a lot of magic power into exceptions that don't exist. They just aren't useful, but everyone is taught how great they are that they just assume yes they're better. Sort of like OOP.
      --
      I still have more fans than freaks. WTF is wrong with you people?
    46. Re:Exceptions are suddenly viable? by Bingo+Foo · · Score: 0

      Exactly. The performance penalty is built in whether you plan on coding with exceptions or not.

      --
      taken! (by Davidleeroth) Thanks Bingo Foo!
    47. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0
      But your functions are no longer as simple and orthogonal as they were before. Making sure that your file isn't null is now part of the program logic that shouldn't be dealing with that. It also makes sure that you deal with any problems that could come up. The lazy C programmer philosophy may be to just assume that any end user understands that a null pointer error means that the file could not be found.

      Exceptions can really make complex systems like an OS more manageable. Using C++ even if only for the error-detection capabilities, exceptions, and more advanced type-checking would be worth it if the kernel weren't so far along by now.

    48. Re:Exceptions are suddenly viable? by multipartmixed · · Score: 3, Insightful

      > So why can't openfile() simply return NULL?
      > Obviously an unsuccessful operation.

      Well, you want to communicate back to the higher level code *why* the call failed.

      Oh, wait, no problem!

      Well set a global variable called errno.

      Oh yes, and scratch our heads for a seeming eternity while we figure out exactly how to virtualize different errnos for each thread.

      And hope to hell that no failing system calls get called between when we failed and when the user checks errno.

      Rock on!

      --

      Do daemons dream of electric sleep()?
    49. Re:Exceptions are suddenly viable? by Foresto · · Score: 1
      "Modern (ie, good) C++ compilers get this penalty down under 1%."
      Which ones, on which platforms? Can you post some references?
    50. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 1

      As one can throw more than just an int, you can pass out any relevant info you want.

      You can embed try{} blocks, as well as rethrow the exception.

      Also, my C++ debugger has a little option called "break on exception," which solves the issue.

      --
      Care about electronic freedom? Consider donating to the EFF!
    51. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 1

      oh, so I can just say:

      FILE * bar = openfile ("foo");

      instead of

      FILE * bar;
      if (! (bar = openfile ("foo")) {
      perror ("foo");
      return;
      }

      As it's likely that there is more than one place where I have to handle the same kind of error... abstraction! woah!

      --
      Care about electronic freedom? Consider donating to the EFF!
    52. Re:Exceptions are suddenly viable? by arkanes · · Score: 1

      G++ on x86 (maybe also PPC? I don't know) is the only one I know for sure, but I believe MSVC 7.1 uses a similiar scheme. It's not quite zero overhead, but it's very very small.

    53. Re:Exceptions are suddenly viable? by shadowmatter · · Score: 3, Funny

      Even the Windows kernel developers rejected them as a bad idea.

      MS Developer #1: I was thinking we could put exceptions in the kernel.
      MS Developer #2: Are you insane? Why on earth would you want to do that? I don't think I've heard a stupider suggestion for a kernel addition.
      MS Developer #1: Really? Well uhh... how about we put an Internet browser in the kernel?
      MS Developer #2: FREAKIN BRILLIANT, let me call Bill.

      - sm

    54. Re:Exceptions are suddenly viable? by E_elven · · Score: 1
      But your functions are no longer as simple and orthogonal as they were before. Making sure that your file isn't null is now part of the program logic that shouldn't be dealing with that.

      I don't see how that follows, unless you mean that the error wasn't handled within openfile()? (That was because the GP specified this scenario.) You still have to have the error handling code somewhere.
      --
      Marxist evolution is just N generations away!
    55. Re:Exceptions are suddenly viable? by E_elven · · Score: 1

      You have to have the error handling somewhere. The GP happened to specify the scenario I used. In the end you have to do either a fp != NULL or a try-catch, unless it's a fatal exception which I didn't protest against.

      --
      Marxist evolution is just N generations away!
    56. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      BeOS?

    57. Re:Exceptions are suddenly viable? by manonthespoon · · Score: 1
      Even the Windows kernel developers rejected them as a bad idea. Don't do it. Don't accept any patch that allows it.
      Yeah, every major design decision in the Linux kernel has been based on the design of the Windows kernel. Windows is such a stable and bug free system that they've never made design mistakes!
    58. Re:Exceptions are suddenly viable? by Ashtead · · Score: 1
      You can make functions return more than one value by either having them return a struct, or via a argument passed by reference. Passing and returning structs by value has been ANSI standard since the late 1980s at least.

      Such as this somewhat contrived example:

      /* In a .h file somewhere to be included: */
      struct statusinfo { int errcode, wherebroke; };

      /* then sometime later in a .c file: */
      #include <stdio.h>

      struct statusinfo foo(char *whatever)
      {
      FILE *fp;
      struct statusinfo rstatus;

      fp = fopen(whatever, "r");
      if(NULL == fp)
      {
      rstatus.errcode = errno;
      rstatus.wherebroke = __LINE__;
      return(rstatus);
      }
      /* Do something or other with what is found in the file */

      fclose(fp);
      rstatus.errcode = 0;
      rstatus.wherebroke = __LINE__;
      return(rstatus);
      }

      Adding variables to the struct statusinfo for the file-name and maybe the function name is left as an exercise -- you get the idea.

      --
      SIGBUS @ NO-07.308
    59. Re:Exceptions are suddenly viable? by Pete · · Score: 1

      The second is dead wrong- to ignore an exception, just catch all exceptions and do nothing. I know a lot of programmers who do just that to get rid of exceptions they can't fix.

      Heh. Yeah, I've heard of that happening quite a lot in Java (not so much in C++, but still to some degree). There's two points I'd make about that:

      1. To ignore an error/exceptional-condition indicated by the return code of a function, you literally don't have to do anything. You have to do something active to respond to the "message" indicated by the retval, but you don't have to do anything to ignore it.

        With a C++-style exception (and, indeed, most exception systems I know of) you have to do something active to prevent an exception propagating further up the call stack. So you must do something in order to "ignore" an exception outcome - which effectively means that you're not ignoring it :).

        It might seem like I'm splitting hairs here, but it is an important distinction.

      2. Just catching exceptions and blithely going on as though nothing went wrong is not safe - no more than it's safe to ignore an error retval from a "normal" function. Programmers don't (normally :-)) throw pointless exceptions just for the hell of it. The whole point of a function throwing an exception is to indicate "I couldn't do what I'm supposed to do" and usually to give you some useful information as to why.

      [AuMatar also said:]

      Thats a bug in constructors, not a valid reason for exceptions.

      Heh. I'll let you argue that point with Bjarne. :-)

      In any case, if you really want to "return" a value from a constructor, you can do it in the same way you can for any other function with a void return type. You can add an extra reference parameter, eg.

      void square(int a, int& retval) { retval = a*a; }

      Yes, it's grotesque - but then so are many other cases where it's natural to return a single value from a function, but the user ends up having to check that returned value just to make sure it's not an error code. The common thing with many POSIX functions being that a retval greater than or equal to zero is a valid return, while something less than zero (or specifically -1) indicates an error (the specific details of the error indicated by an external global variable).

      The really nice thing (from my coding perspective) is that when the exception system is used properly, it really facilitates cleaner and clearer code. You can have functions for which the signatures are appropriate and make sense - and you don't have to tie yourself in a knot to handle exception/error situations appropriately.

      I still think you haven't quite "got" the whole point of exceptions (I'm not trying to say you're an idiot or anything, mind). I hoped the "Blub Paradox" pointer would indicate more effectively what I meant, but I guess not. If you'd done any programming with the Qt signal/slot system (or the similar-ish Boost.Signals library) you might have a better idea of how using an alternative control flow is a useful concept (though I'm probably drifting away from the main point now :).

      I have a similar thing with continuations - I just don't get them, I can't understand what they're good for. I haven't yet found (and comprehended :)) an programming problem solved using continuations for which I couldn't see (what I thought to be) an equally elegant alternative solution.

      But I'm willing to accept that there is something to them that I just can't see yet - if only because I'm quite happy to say that the kind of people involved in that sort of language design are almost certainly way way smarter than me. :)

      I think you're

    60. Re:Exceptions are suddenly viable? by hobo2k · · Score: 1

      It isn't just performance, but also correct handling of errors. If exceptions are allowed to pass through a function, the developer must always be careful to ensure any cleanup code is not skipped (i.e. liberal use of destructors).

    61. Re:Exceptions are suddenly viable? by GenSolo · · Score: 1

      'File Not Found' - which file?
      The exception object should contain this information. If it doesn't, that's not a problem with exceptions but rather a problem with the programmer who threw a bad one. It's pretty much the same problem as any other class that lacks an important interface component.

      which function?
      Well, this can be included in the exception but it shouldn't be necessary if you know which file.

      Why, exactly?
      As if the function throwing the exception knows that?

      You see, the reason we throw exceptions is that we can't clean up where we are. If the function throwing the exception could fix itself, it would do so and move forward. Otherwise, it should throw an exception object containing all the relevant information. Unlike integer exit codes, exceptions are full-blown objects with whatever interface and data their designer builds into them.

    62. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      These can be expected to happen in the ordinary operation of the program.
      I'm not sure why you got modded troll, but oh well. I just wanted to add that the reason an exception can be expected to happen in the ordinary operation of the program is this: users do things they shouldn't. A "file not found" error should be expected to happen frequently because the user can mistype a filename or simply assume a file exists that was deleted by someone else yesterday. Should this normally happen? Well, no; thus, it's exceptional. QED, of course.

    63. Re:Exceptions are suddenly viable? by cout · · Score: 2, Insightful

      An uncaught exception is a kernel panic. By contrast, an unknown error return is still an error, and usually the right thing happens.

      An uncaught exception results in a call to unexpected(), which by default calls std::terminate(). This behavior can be overridden using std::set_unexpected() to, for example, return an unknown error to the caller of the currently executing system call.

    64. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 1, Informative

      Stop talking out of your ass. The Windows kernel developers use structured exception handling that was developed during the OS/2 days. The resulting code ends up nice looking and manageable because unlike C++ exceptions, this one also handles hardware exceptions (among other nifty features).

    65. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      Frankly, code that doesn't check the return status code doesn't belong in the kernel. I guarantee that a panic from an uncaught exception would be easier to fix. It is a brutal way of letting you know the control flow logic in your code is broken.

    66. Re:Exceptions are suddenly viable? by Lord+of+the+Fries · · Score: 2, Interesting

      This is very interesting to me. I'm reading this as a novice kernel programmer, but an adept application level programmer with a variety of OO languages used (Smalltalk, C++, OCAML, Objective-C, CLOS). I have to say... C++ is by far the worst realization of the ideals behind OO that I am aware of. That's beside the point though, what I guess I find interesting, is why didn't Apple choose to inject some Objective-C into the kernel (a much better C-OO hybrid). I was not aware they used C++ in the kernel before your post.

      --
      One man's pink plane is another man's blue plane.
    67. Re:Exceptions are suddenly viable? by that+_evil+_gleek · · Score: 1

      I couldn't find who you qouted there... but I had to comment: 'orthogonal'?
      I thought that had to with language design, and syntax, I'm kind of hazy on it actually, but I thought it was like
      being able to use syntax basically any way you want, and if you say couldn't do an if() inside a for(), but could
      do a for inside an f then it wasn't. I'm kinda thinking exceptions lead to less orthogonality since it lead to uncatched exceptions are syntax errors if anything... But, actually I thought it was just a term Computer Science professors made up to generate a more diffuse grade distribution ;-] ( And impropery overloaded the term from math as well! )

      But what does it have to do with return codes vs exceptions?

      Anyway... Another point, is that exceptions vs return codes can affect design. Take unix programs
      like ed,vi, and emacs, etc: If you try to visit a file and it exists, the prog reads the file in, you edit the buffer, and saves back to that name when you save; if the file doesn't exist, then this is just a simpler case of the general problem, you just don't need to read in. But, trying to the same thing with exceptions, is much more cumbersome, and comes out much less elegant looking source wise, to say the least. At least, that was my experience with java.
      I think the exception mechanism would lead more to the typical windows style program, were newfile is oneaction, and open is another ( and new file buffers stay "untitled' until you save ).

    68. Re:Exceptions are suddenly viable? by zyridium · · Score: 1

      You just dont seem to get it. One clear benefit is that you can write a level of library that does not need to consider exceptional situations and can simply allow them to be handled at a simple higer level in the program.

      Having to marshall back success and failure results through several methods and then branching at each individual point is cumbersome.

      Exceptions allow you to simply ignore any exceptional case that you can not either react to or add contextual information to. Exceptions are not inherently expensive, and I have not seen any engineering reason that they are a Bad Thing. Performance is not the issue that is holding back software today.

    69. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      you're an idiot. MSHTML / IE is not part of the kernel.

    70. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      Exceptions allow you to simply ignore any exceptional case that you can not either react to or add contextual information to. Exceptions are not inherently expensive, and I have not seen any engineering reason that they are a Bad Thing. Performance is not the issue that is holding back software today.

      Exceptions can actually be a performance win - try/catch blocks can conceivably be erected for free and then you can walk the stack & figure out what exception handling is in play by inspecting the IP. So now you get rid of all your error handling code from running unless you truly have an error - offering a performance boost. Now if you have an error like this it'll be slower to handle (the stack walk & table lookups will make sure of that), but error conditoins aren't supposed to happen during normal programs - they're exceptional.

    71. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      You really get to see the advantage of removing the need for complex deeply-nested if(errorcode) statements, once you have

      try {
      try {
      try {

    72. Re:Exceptions are suddenly viable? by dooglio · · Score: 1
      I think the point is that if you're looking at code that has to have multiple nestings of try/catch statements, then it was poorly designed to begin with.

      As was said earlier, exceptions are for exceptional circumstances.

      Besides, multiple nestings of if/else statements point to poor design. So, should we ban if/else as well?

    73. Re:Exceptions are suddenly viable? by Old+Wolf · · Score: 2, Interesting

      Firstly let me say that I'm not a kernel programmer, and I respect the fact that you have decided against using exceptions. However I'd like to attack your arguments anyway, based on my (limited) point of view, so if you could correct me then that would be good.

      The article said that they had modified exception handling to make it efficient time-wise, so the complaint that it's slower than using error returns no longer applies. (Recall that exceptions only should be thrown in exceptional circumstances, not as an expected part of processing; and exceptional circumstances will usually include some handling such as printk() which they noted takes an order of magnitude more time to run than the process of propagating an exception).

      So let's return to your main point: the risk of an uncaught exception causing a kernel panic is too high.
      (BTW how is this different to the risk of a divide by zero causing a kernel panic in C ? )

      I'd like to make a 'case study': accessing the elements of a std::vector. If you're unfamiliar, then writing:
      v[n]
      is equivalent to using that syntax on an array of ints. However, writing:
      v.at(n)
      is equivalent to writing in C:
      if (n > v_size)
      return some_error_code;
      v[n]
      and then having handling in the caller function for the possibility of that error. Much more concise, don't you think? Especially if you have
      several of these accesses in one expression.

      (Presumably the 'n' would come from some external source that is expected to be in bounds but occasionally may not be. )

      So you have reduced code complexity by not having to do a manual bounds check everywhere. You have no added runtime overhead in the case of the value being in range.
      Also, the case of the uncaught exception is just as bad as the case of an out-of-range array access -- maybe even worse, as it will take longer to find the bug.
      And perhaps the most important: you have the flexibility of being able to put the error handling code at a higher level than just the parent function. In the cause of the completely uncaught exception, at least you have the exception error message to indicate exactly what went wrong. If the kernel crashes from an out-of-range array access you may have no idea what went wrong, especially if it is in a tricky bit to use a debugger.

    74. Re:Exceptions are suddenly viable? by gbjbaanb · · Score: 1

      Of course the word 'never' is totally inappropriate since by definition exceptions _are_ designed to be thrown.

      an analogy for you: my car has airbags, which are obviously designed to go off. But they shouldn't be used everytime I hit the brakes hard.

      You see, many people simply use exceptions as a replacement goto. the 'clean code with error handling' is often just another way of writing 'goto end'.

      I think it's perfectly normal and acceptable to have an exception be an everyday occurrence
      Absolutley not. Use normal error handling for those errors. Use exceptions for those things that you do not expect to happen but have to handle. FileNotFound is not one of those things (IMHO). FileNotFound after you've opened it and are reading from it... is.

      I was a little contentious in the post, but I hope it makes people think a little before just using exceptions as error handlers. (especially if theyre used like VB's On Error Goto :) )

    75. Re:Exceptions are suddenly viable? by drawfour · · Score: 2, Interesting

      That's what pointers are for. Instead of:
      FILE *fp = fopen("foo.txt");

      why not use something like a return code for errors and out parameters of the functions. No globals, no worries about catching exceptions, you just return an HRESULT.

      HRESULT hr = S_OK;
      FILE *fp = NULL;
      hr = FileOpen("foo.txt", &fp);
      if (FAILED(hr)) ...

      This is NOT that hard. Plus HRESULTs can be easily propagated down, and ANYONE can act on a failure if he desires with or without knowing what the failure is.

      If you use exception handling the way it's supposed to be, you catch OBJECTS and not the wonderful catch-all of "...". The problem with using the catch-all of "..." is that truly BAD events like stack overflows are caught. And if you do not know how to recover from a stack overflow, you better abort the program immediately.

      But if you DON'T use the "..." form, and you don't know of ALL types of exceptions that can be thrown... well, one will slip by you and a regular "exception" will just kill your process since it's not handled. I MUCH prefer HRESULTs to handle known and unknown errors. Let a truly bad exception kill my program, and let me handle return codes.

    76. Re:Exceptions are suddenly viable? by abdulla · · Score: 1

      Why isn't the exception containing which file was not found? And possible which function threw it. If you want to go overboard, you can do what the Unreal Engine does (or did) and generate a call stack when an exception is thrown.

    77. Re:Exceptions are suddenly viable? by AaronLawrence · · Score: 1

      What's overboard about a callstack? They are brilliant. Every language should log out a callstack in a controlled fashion, for unhandled exceptions.

      --
      For every expert, there is an equal and opposite expert. - Arthur C. Clarke
    78. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      What if your function has two possible places where it can return NULL? How do you know which one of those two possible conditions caused the NULL to be returned? You can't know; you only have one peice of information to go by. Exceptions are far more powerful; you can throw two different exceptions; one for each possible condition, and catch and handle each exception individually.

    79. Re:Exceptions are suddenly viable? by cow-orker · · Score: 1

      But note that the same considerations apply to C with the added complexity that you have to explicitly propagate your error code. Also note that error checking in C does cost performance, too, even if no error occured.

    80. Re:Exceptions are suddenly viable? by IamTheRealMike · · Score: 1
      Agreed. Saying "exceptions have no place in the kernel" is stupid - a good table-based exception ABI can be have zero cost except when an error occurs. It's not one or the other, if you're expecting a call to fail frequently use an error code return.

      Windows SEH is really quite neat, and sometimes I wish Linux had a similar feature (though I'm not convinced the complexity is worth it). The Windows kernel actually converts access violations/illegal instructions etc into exceptions and then unwinds the user-mode thread stack. You can throw/catch exceptions from C.

      I think a lot of people who don't like exceptions probably don't understand exception safety properly, or were brought up on Java exceptions where every method ends up with "throws Exception" on the end to hack around checked exceptions.

    81. Re:Exceptions are suddenly viable? by Duhavid · · Score: 1

      The "collected exception handling in one place" model usually leads to

      A: Poor or ugly error reporting. Usually it is difficult to figure out what line above threw the error, so the report devolves to "something bad happened". It is then difficult to figure out what did happen. In the cases where the main body throws disjoint exception types, obviously this would not be the case, but you would have a large number of catch blocks, one for each type that could be thrown.

      B: Poor or ugly cleanup. Deallocating everything that was allocated in the main body can be interesting. If everything is "deallocated-in-destructor", then you are safe.

      --
      emt 377 emt 4
    82. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      I know. But the point was, you could see it happening like this, right?

      - sm

    83. Re:Exceptions are suddenly viable? by Carewolf · · Score: 2, Informative

      What he is saying is that exceptions should only be used as runtime assertions.

    84. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      catch is not supposed to catch any hardware exceptions or signals. They're only supposed to catch exceptions being thrown from a throw statement. I assume you're using Microsoft's compiler because their implementation wrongly does things like that (I think there was a workaround, search google groups for it).

      I agree though, you should never use catch (...) unless you *really* know what you're doing (read Herb Sutter's books if you need the reasoning).

    85. Re:Exceptions are suddenly viable? by BCoates · · Score: 1

      No, unexpected() is called when a function violates its exception specification. Throwing an exception with no handler down the stack causes terminate() to be called directly, and doesn't even guarantee the stack is unwound first. terminate() can be overridden, too, but I doubt you could do anything more useful in it than log an error and panic.

    86. Re:Exceptions are suddenly viable? by cout · · Score: 1

      You're right, it is terminate that gets called, and what's worse, the standard doesn't guarantee that the stack gets unwound when terminate is called. After terminate is called, it would be a bad idea to force the stack to be unwound, and it would be a bad idea to not clean up resources by unwinding the stack. So scratch my original idea and just catch(...) for every system call. This is what I do when I wrap C++ code with Ruby, and it works pretty well.

    87. Re:Exceptions are suddenly viable? by MarkCollette · · Score: 1

      I now see why this argument is at an impasse.

      Basically, C++ exceptions simplify error handling code in intermediate functions by doing some hidden processing, which is slower than the existing if..goto solution.

      The hypothesis is that the simplicity will reduce bugs and be more maintainable.

      I've only done a little kernel programming in OpenBSD, but I've done a lot of Java and C++ programming, which means that I think I can speak from both perspectives.

      First off, until this fork can show little to no reduction in performance, it is not wanted in the main branch. This is one way that application software is different from system software. There is no throwing hands up in the air with a shrug and saying, "oh well, we just lost 7% performance, but who will notice?"

      There is not a tradeoff of ease of programming for performance in kernel programming. Instead kernel programmers employ a different tradeoff: if you can't handle the difficulty, then goodbye. Perhaps your response will be that "aha, but then they'll just have more bugs!" Well, in theory yes, but in practice, not as much as application software, because there are stricter controls, and everyone involved is better than average.

      But, let's explore this relationship between simplicity and bugs a bit more. A kernel is debugged more than an application. Which means that someone is single stepping through code more, not just through the code when it works, but specifically when it's not working, when errors are occuring. Which do you think they would prefer: to go through less code, which has special handlers behind the scenes that automatically jump up several functions, or to go through more code but each thing that happens directly corresponds to the source in front of them, where every nuance is presented specifically.

      Maybe one could argue that the exception would somehow reduce bugs more than the current way is better at actually fixing them. But, in the end, bugs will happen none-the-less, and I know which system I'd prefer to have when trying to fix them.

      So, to attack the nomenclature of the proponents of exceptions, which is actually "simpler", less source code, or source code that more precisely matches the executable code?

    88. Re:Exceptions are suddenly viable? by dgatwood · · Score: 1
      I didn't say code that didn't check the return status. I said "an unknown error return". Those are completely different things.

      If functionA calls functionB and doesn't care why functionB failed, it usually amounts to:

      if (functionB()) {return error;}

      This is much harder if you have to worry about a half dozen potential exceptions, and if a function adds another one in a newer version, you're screwed. By contrast, you can always add a new return value for any function that follows the pattern of "0 is success".

      Thus the C++ exception model is bad for binary compatibility as it means that either A. you are locked into your list of exceptions for a function (and anything that it calls) as soon as that function becomes public or B. you have to add compatibility shims to mimic the old behavior.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    89. Re:Exceptions are suddenly viable? by dgatwood · · Score: 1
      Well, NeXTstep and Mac OS X Server 1.0 both had Objective-C in their driver stacks (DriverKit). I'm not sure why the I/O Kit design went with C++, beyond possibly that more people know C++.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    90. Re:Exceptions are suddenly viable? by dgatwood · · Score: 1
      C++ Vectors aren't commonly used in most OS kernels, for one thing, as most of the C++ standard library doesn't exist. You'd have to roll your own, AFAIK.

      Stack stompers are the worst to debug, as you note, but they're more frequently (in my experience) caused by an uninitialzed and/or stale value in a pointer than by an out-of-bounds array reference, at least in the kernel. Your mileage may vary. The reason for this is that SIMD-like operations in the kernel (where vectors and arrays are useful) are pretty rare. Arrays are usually very small, and most array indices are explicit in the code (or iterated) rather than being passed in as data from some outside source. Again, your mileage may vary.

      That said, the real question was whether allowing an error to jump out multiple levels to avoid having to explicitly check for an error return makes sense in the kernel. IMHO, generally, you want to check the values in as many places as possible and take corrective action as early as possible. Once you're in some deep nested operation and something goes wrong because you passed in 9 where the limit was 8, bad things have probably already happened elsewhere. The failure may or may not be correctable. As such, you probably want to catch it long before it gets that far.

      The big reason for not doing (C++) exceptions (outside of system calls), though, IMHO, is long-term code maintenance issues. For example:

      A kernel extension calls function A that calls function B that calls some private function C. The performance of B is poor, so that is replaced by a new block of code, D. D is written differently, and for optimal debugging, should return additional error codes.

      With error returns, this is easy. Code that checks "if (A())" for an error still works even if you add additional result codes. While it may not be able to identify what went wrong, this is usually not important at the kernel level beyond the need to print debug information.

      With exception mechanisms, though, the kernel extension has to be modified to catch the new exception. If you had some generic handler, what would it do? Print an error message? If it unrolls the stack, back to where? The extension clearly needs to know that something went wrong, but do you assume that the outermost try/catch block should catch all exceptions? The innermost? With any choice, you'll get it wrong most of the time. It's the kind of thing that can only really be determined when writing the code, not when executing it.

      Just my $0.02. These don't necessarily represent the opinions of my employer (or even myself). :-)

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    91. Re:Exceptions are suddenly viable? by dgatwood · · Score: 1
      With exception mechanisms, though, the kernel extension has to be modified to catch the new exception.

      I should restate that. The C++ mechanism isn't as awful as most exception mechanisms, so it may or may not require modification, depending on whether someone chooses to do a catch-all (e.g. catch(...)).

      Still, if the only real benefit is being able to avoid checking return values from a function, I fail to see the value. More often than not, in the kernel, you need to do some little bit of cleanup in almost every function as you unwind the stack from a failed operation.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    92. Re:Exceptions are suddenly viable? by tshak · · Score: 1

      Exactly. The performance penalty is built in whether you plan on coding with exceptions or not.

      This is correct. The point of my post was to address the issue that the use of exception handling does not incur a performance hit. A try...catch block has zero impact on performance in Java.

      --

      There is no longer anything that can be done with computers that is nontrivial and clearly legal. -- Paul Phillips
    93. Re:Exceptions are suddenly viable? by arkanes · · Score: 1
      Exceptions are actually faster than if/goto in the non-error case, because they avoid conditional checks. They are slower than standard return checking in the error case, which is a reason they shouldn't be used for expected conditions like EOF when reading.

      Exceptions offer little to no benefit in cases where the error checking is simplistic (including all the cases used as samples in these threads). It's where the error checking is complicated and involves duplicate code (there is plenty of this in the kernel) that you see benefit. There is also gain by minimizing the use of conditionals.

      As for how closely the code matches the actual execution... well, C doesn't neccesarily map it either. I'm not sure if you were the poster who said that code should read line by line, just the way the computer executes it or not, but the fact is is that very few non-trivial programs have _no_ parellelism in them. Certainly this is not the case with the kernel.

      These guys say they've dropped execution overhead a whole bunch. Is it enough that it's worth simplifying the code? Is it possible that removal of all the conditional checking involved could actually create a net increase? It's possible.

      As for debugging.. I don't know how well kdbg handles that sort of thing. I rather suspect it doesn't handle it at all, so thats a very valid point and debugging tools would need to evolve to handle that sort of thing. On the other hand, exceptions can make it a lot easier to do printf() style debugging (with minimal overhead if you don't want debugging, no less) by including the debug code in an exception object. I have no idea if that would be practical in a kernel, though.

      I wouldn't except to see this in the main branch for quite some time, if ever.

    94. Re:Exceptions are suddenly viable? by Anonymous Coward · · Score: 0

      This is very funny, I thought you were kidding!.

      Then I read the other comments you post and I saw you have no clue about error handling using exceptions. Stick with your error codes but don't blame a technique you don't have knowledge.

      Fine enough to send this to all Java, C++, Python, Haskell, C# language designers and say them they are all wrong for using exceptions. This is my Moron of the day bookmark. Wake up or you'll be unemployed soon...

    95. Re:Exceptions are suddenly viable? by abdulla · · Score: 1

      It's more the way the Unreal engine implements it (last I looked), which is by putting a macro at the start and end of every function that can be in the path of an exception (possibly any function), which effectively translated to a try/catch clause around everything which would append the function name to a string in the exception. Though the cost of exceptions and try/catch clauses has gone down, it seems rather unwieldy to me. Ofcourse there's another method via using debug symbols, but that requires sending your program out with debugging information.

      It's all a very neat idea, but in practice it doesn't seem like the best cleanest solution to me.

    96. Re:Exceptions are suddenly viable? by ankhcraft · · Score: 1

      In Java, which doesn't have destructors, it's even worse because you've got exceptions with no automatic cleanup, which means you've got to have all sorts of ugly nested try/catch/finally and state management.

      Java has finalize () instead of destructors, which is run once the garbage collector determines that it is safe to reap the object. This may not be good enough for expensive resources such as socket connections, etc., but it DOES allow cleanup upon destruction of the object.

      Furthermore, suggesting that the lack of a destructor causes cleanup in response to exceptions to be ugly is nothing but a shortcut to thinking. All you need is:

      SomeObject o = new SomeObject ();
      try {
      o.doSomething ();
      } finally {
      o.cleanup ();
      }

      Why is explicitly showing in your code that the object gets cleaned up, exception or no exception, ugly? Personally, I think that this is good code for a production environment. It's self-documenting: immediately the reader knows that the object has resources that must be cleaned up after use. It also shows the would-be paranoid, that no matter what happens in the body of the try block, this object is going to be cleaned up after use. QED.

      Honestly, my favorite programming language is C, but for a production environment, the best one is Java for reasons of code maintenance, reusability, readability, and many other reasons. I'm sorry, but if C++ was the cat's a$$, then companies would be using it instead. In practice, projects written in Java eat up less man hours and are much easier to maintain, even for Junior to Mid-Level programmers.

      Do you want to be the one cleaning up a junior or mid-level programmer's dangling pointers because he is just too intimidated and too frustrated to do it effectively himself? I sure don't.

      In an ideal world, the most efficient language would win. And that language would NOT be Java. ;-)

      --
      ...
    97. Re:Exceptions are suddenly viable? by arkanes · · Score: 1
      Wasn't going to reply as this is an old thread, but what the hell.

      1) Java's finalization is non-deterministic, which makes it totally non-suitable for resource cleanup. There's no way to tell when a resource will be released and in fact there is no guarantee that it will EVER be released aside from program termination. This is what is called a "resource leak".

      2) Because the designers of Java know this, they have try/finally instead, so you can explicitly clean everything. This is a problem because there's more changes for programmer error (admittedly a fairly minor case), but more importantly because you end up with enormously deep layers of complex nested try/finally and state managment code. C++ style exceptions would be cleaner and also perform better (stack unwinding and objects removes the need for explicit managing of state, fewer try blocks means less stack overhead).

      Java is better because it's successfull? Sure, by some metrics. Java is popular because it's adequate. It's a lot like VB - it's not "good". But it's good enough, the bar to entry is shorter and you can throw a lot more hardware at the problem. I've seen a ton of mission critical applications written in Access. Not in VB using Access, mind, but actually in the Access form/scripting front end. Does that mean Access was the best choice for that application? Of course not. In my professional experience, roughly zero design decisions are based on objective merit. C++ isn't perfect. You do need better developers. You do need a longer developlment cylce. There is less handholding and mistakes can cost you more - you'll crash rather than simply performing badly. Companies like this cause they can skimp on QA and throw hardware at problems instead, and that's a viable alternative. But it offends the asthetic in me, which is why I like C++.

    98. Re:Exceptions are suddenly viable? by ankhcraft · · Score: 1

      1) Java's finalization is non-deterministic, which makes it totally non-suitable for resource cleanup. There's no way to tell when a resource will be released and in fact there is no guarantee that it will EVER be released aside from program termination. This is what is called a "resource leak".

      2) Because the designers of Java know this, they have try/finally instead, so you can explicitly clean everything.

      Reponse-to-1)
      Well, of course I realize that it's not the same and can leave resources lying around. That's why I mentioned that it wasn't suitable for expensive resources in my previous post. ;-) Obviously, this also means that it's not suitable for things that must be cleaned up.
      Also, it's worth mentioning that although the garbage collector is non-deterministic, if you leave a method with an object on the stack that has no references to it elsewhere... this object will be reaped very soon.

      Reponse-to-2)
      try/finally does *not* exist for the reasons you mentioned. It exists for exception handling. Not as some workaround for the lack of a destructor. The discussion that we've been having which links them is situational, not representative the "real purpose" of try/catch/finally blocks.

      Reponse-to-your-summary)
      Well, I actually agree with you so there's not much need for discussion here. I stand by what I said in my previous post. Java is a much better language than C/C++ for the vast majority of (but not all) business purposes, but C is still my favorite language.

      --
      ...
  9. Stillborn. Seriously by apankrat · · Score: 3, Funny

    Java on other hand ...

    Or better yet - Brainf*ck, my personal favourite :)

    --
    3.243F6A8885A308D313
  10. Great news! by Anonymous Coward · · Score: 0

    This can only be viewed as a good thing.

    I know that code I produce in C++ is by far more sophisticated, and of a much greater quality standard than what I could produce in C in a similar time frame.

    I hope that this will be the beginning of some new more sophisticated features for Linux!

    1. Re:Great news! by AuMatar · · Score: 3, Insightful

      Thats because you're used to C++. I know that code I produce in C is by far more sophisticated, and of a much greater quality than what I could produce in C++ in a similar time frame (unless I used the C subset of C++, which basicly means I was writing C).

      Now if you were to start a new kernel entirely in C++, that'd be fine. The use here would be to mix the two *shudder*. No thanks. You then have a problem where the C++ people can't understand the C code, and the C people don't understand the C++ code. Its a maintenance nightmare. Just wait til the first patch that requires changing C and C++ parts. It'll be ugly.

      Its much better to pick 1 language for a project and stick with it, or do a total rewrite. Mixing the two will just cause problems. Luckily, this patch has near 0 chance of being taken into the kernel.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    2. Re:Great news! by Anonymous Coward · · Score: 0

      The whole purpose of Object oriented programming is to help when programming with multiple developers. So of course anything YOU can code would be faster to program in C since yor background is in that.

      In the end I agree with you statement about multiple languages. Still this could be useful for device drivers or things that interoperate within the kernel but are seperately maintained by say a small company with limited resources. But I don't know my expertise isn't in that area. Still it might not bad so long as it's use is limited and not in the kernel main.

    3. Re:Great news! by AuMatar · · Score: 1

      Object oriented programmign doesn't help multiple developers code faster. Encapsulation does, but thats not a property of only OOP (nor does OOP ensure it). Good code has it, bad code doesn't regaruless of language. So it boils down to what the team knows- if the team is more experienced in C++, C++ will code faster. If the team is more experienced in C, C will be faster.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    4. Re:Great news! by cheekyboy · · Score: 1

      If your a C++ coder that cant understand C, then your in a more sorry state. By default how can you not understand it? You can still use all the C isms in C++, just use the part of C++ that is best suited, ie classes/objects... ignore the rest of c++ that you find too complex and do C style coding inside your classes using a small part of C++.

      If you understand how C++ gets turned in C and how C gets turned into ASM, then your good (like me), but you dont, then stick to making dicky web apps/asps.

      --
      Liberty freedom are no1, not dicks in suits.
    5. Re:Great news! by Anonymous Coward · · Score: 0

      There's a misconception that ISO / ANSI C is a perfect subset of ISO C++. There are different type rules, scoping rules, etc.

    6. Re:Great news! by Eisvogel · · Score: 1

      > Its much better to pick 1 language for a
      > project and stick with it, or do a total
      > rewrite. Mixing the two will just cause
      > problems.

      Randomly Mixing languages is indeed a nightmare.

      But I suggest you have a look at big projects like(gcc, GNU kernel ...). You'll notice that many if not all mix languages. If done wisely the advantages of both languages - e.g. C & ASM - can solve dificult tasks quite nicely.

  11. Great news, I hop by Anonymous Coward · · Score: 4, Interesting

    That's really awesome news, but I just can't imagine it being accepted in the mainline branch. Many figureheads in the linux kernel group are anti-C++ enough to probably veto this effort. (If "anti" is too strong, then at least I'll safely claim they're not "pro C++".)

    It'd sure be nice though...

    1. Re:Great news, I hop by colinleroy · · Score: 1

      It'd sure be nice though...

      No, it wouldn't.

      --
      blah
  12. Perl by Anonymous Coward · · Score: 0, Funny

    When can I submit my Perl patches to the kernal? I am waiting for that.

    1. Re:Perl by CanadianCrackPot · · Score: 1

      Isn't the kernel obfucated enough?

      --
      Good programmers drink beer to relieve job stress.
      Great programmers drink hard liquor and work best hungover.
  13. full article text, just in case by Anonymous Coward · · Score: 2, Informative

    C++ in the Linux Kernel

    We have implemented a complete kernel level run-time support for C++ in the Linux kernel. In particular our run-time support enables the full use of C++ exceptions in the Linux kernel, but notably also includes support for global constructors and destructors, and dynamic type checking. Our kernel level support is based on open source commodity components, specifically the GNU gcc/g++ compiler and its exception implementation, the C++ ABI version independent standard interface.
    C++ runtime support for 2.6.6 (Last update 27 october 2004)
    C++ runtime support for 2.6.9 (Last update 27 october 2004)

    Using the C++ runtime support for Linux
    Installing the C++ runtime support for Linux

    The code is installed by applying a patch to the Linux kernel and enables the full use of C++ using the GNU g++ compiler. Programmers that have used C++ in Linux kernel modules have primarily been using classes and virtual functions, but not global constructors. dynamic type checking and exceptions. Using even this small part of C++ requires each programmer to write some supporting routines. Using the rest of C++ includes porting the C++ ABI that accompanies GNU g++ to the Linux kernel, and to enable global constructors and destructors.

    The implementation of the C++ ABI is based on the implementation provided with the source of the GNU g++ compiler. We modified it to run in kernel space, and performed optimizations that reduces the cost of exceptions and dynamic cast considerably. Our paper contains thorough explanations of these optimizations. The cost of throwing an exception one level on a 990 MHz Intel Pentium is around 12-13 micro seconds in the plain GNU g++ implementation, which we reduced to 2.1 micro seconds by modifying the runtime library, including unwinding the stack in one phase, and caching information on exception paths. In contrast the cost of a trivial printk operation -- printk("Error\n") -- is 18 micro seconds.

    In addition, we modified the linux kernel module loader to handle C++ weak symbols correctly. GNU g++ associates with each class a type information object that encodes the type of the class as a mangled string and puts a pointer to this object in the virtual table for the class. GNU g++ uses weak symbols to reduce the dynamic type checking to a pointer comparison, thus avoiding the more expensive string comparison. Each time a class, containing virtual functions, is used in a source file, GNU g++ generates the virtual table, type information object and type name string as weak symbols and the user space linker ensures that there is only one copy of this object, which renders the simple pointer comparison sufficient. However, the kernel module loader, which in the 2.6 versions of the kernel is exclusively in kernel space, does not handle these weak symbols correctly and always relocates references to weak symbols to the weak definition within each object file that is being loaded. Therefore multiple type information objects may exist for the same class and pointer comparison becomes insufficient when doing dynamic type check across kernel modules. To avoid this overhead we have modified the kernel module loader to handle these weak symbols; the first time a weak symbol is encountered it is added to the symbol map, and on subsequent encounters the relocation is done to the first symbol.

    Paper:
    Exceptional Kernel: Using C++ exceptions in the Linux kernel
    Halldor Isak Gylfason, Gisli Hjalmtysson
    Submitted for publication October 2004 abstract

    Please direct bug reports, questions and comments to {halldorisak at ru dot is}

  14. RMS by zoeith · · Score: 5, Funny

    RMS is probably turning over in his grave... oH! wait he's not dead!

    --
    Zoeith
    1. Re:RMS by MerlinTheWizard · · Score: 1

      Don't you all forget this is just some "obscure" research project. It might get some university's CS laboratory something to publish. Not the same as saying this will have any practical use whatsoever. That being said, I'd rather see Microsoft rewrite the Linux kernel than it being rewritten in C++. That says it all. Shall we create a new " Do not touch my Kernel! " petition? ;-)

    2. Re:RMS by m0rph3us0 · · Score: 1

      I thought RMS was a big LISP fan. I've always sensed that he regarded C as primative as ASM.

    3. Re:RMS by Anonymous Coward · · Score: 0

      That's strange, I thought Windows NT was written in C++.

    4. Re:RMS by Anonymous Coward · · Score: 0

      RMS used to do a lot of Lisp programming and liked it. He used C for a lot of GNU stuff because it was a pragmatic choice at the time, but I'm pretty sure he doesn't consider it the pinnacle of language evolution for kernel development.

    5. Re:RMS by Anonymous Coward · · Score: 1, Funny
      RMS is probably turning over in his grave...

      Heh heh funny! IQ estimate: 115

      oH! wait he's not dead!

      Oh dear, revised IQ estimate: 85

    6. Re:RMS by IntergalacticWalrus · · Score: 3, Funny

      ...yet.

    7. Re:RMS by Anonymous Coward · · Score: 0

      HURD: "But I'm not dead yet!"
      RMS: "WHat was that?"
      Linus: "That was nothing.Here ye go."
      RMS: "He said he wasn't dead yet."
      Linus: "Yes he is."
      HURD: "I am not!"
      RMS: "I can't take him like that!"
      Linus: "He'll be dead soon. Can you wait?"
      HURD: "I Think I'm getting better!"
      Linus: "No you're not."

    8. Re:RMS by MerlinTheWizard · · Score: 1

      Not so, I think it's almost 100% C, with some assembler here and there where low-level platform-dependent stuff is needed. The Win32 API and the DDK are practically a living proof of that. For one, you won't find any C++ sample code in any of the MS documentation, except maybe in some strange DirectX and COM samples... but then again, I think it's mainly because DirectX uses COM. COM seems to be indeed C++ stuff, for the most part. COM is not the Windows kernel.

    9. Re:RMS by Anonymous Coward · · Score: 0

      RMS is probably turning over in his grave... oH! wait he's not dead!

      I've filed a bug report.

    10. Re:RMS by Anonymous Coward · · Score: 0

      No, he just smells that way...

  15. Progress by caseih · · Score: 4, Interesting

    Say what you will about C++ being slower and more bloated than C, but I think this is a huge leap forward. I doubt Linus will accept it anytime soon as an official patch, though. If they have succeeded in making exceptions quick, I think C++ has a real place in the kernel. C++ offers the ability to have better type safety and more modular apis and interfaces to the kernel. For example being able to develop a new device driver inheriting from a nice base class is a good idea.

    Anyway, this is a neat hack and I look forward to seeing what comes of it.

    1. Re:Progress by alienw · · Score: 4, Informative

      Nothing will come out of it, for the simple reason that C++ does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

    2. Re:Progress by fitten · · Score: 5, Insightful

      In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      Yeah, who wants a common driver API for video, network, or sound cards...

      Not to mention that drivers are all about abstracting the hardware and interface implementation from the OS itself anyway...

      The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

      Yes, a kernel is more difficult than a word processor, but that doesn't mean that implementors must implement stupid C++ code. You can do some pretty neat things in C++ if you know what you are doing. If you don't know what you are doing, you can do some pretty crappy things.

    3. Re:Progress by Lally+Singh · · Score: 1

      Of course not. That's why we use assembler... oh wait...

      Besides, the abstractions are already there, only they're not supported by the language. Look at device drivers: they're polymorphic classes, only that there's no checking that the compiler can do.

      --
      Care about electronic freedom? Consider donating to the EFF!
    4. Re:Progress by Vlion · · Score: 0, Flamebait

      hahaha.
      You _don't_ use C++ that much, evidently.
      And, you OBVIOUSLY havn't read Linux kernel code.
      Obfuscation and opacity are its hallmarks.

      I'll read a LISP kernel before I read a C kernel, given the choice.

      --
      /b
      |f(x)dx = F(b) - F(a)
      /a
    5. Re:Progress by pchan- · · Score: 1

      while i generally agree with you, here is a special case:

      the haiku os (formerly OpenBeOS) kernel is partially written in C++, especially the BFS filesystem implementation. but there's a catch! they don't use many of the features of c++ that make it bad for just these kinds of things. no exceptions, no virtual functions, no STL, none of that other nonesense that c++ does behind your back.

    6. Re:Progress by IceAgeComing · · Score: 4, Insightful

      In a kernel, all the code needs to be transparent,

      That got a chuckle from me. I know what you meant, but after looking at the following (randomly chosen :) block from the device driver grip.c, I wonder just how "transparent" it is:

      if ((((u ^ v) & (v ^ w)) >> 1) & ~(u | v | w) & 1) {
      if (i == 20) {
      crc = buf ^ (buf >> 7) ^ (buf >> 14);
      if (!((crc ^ (0x25cb9e70 >> ((crc >> 2) & 0x1c))) & 0xf)) {
      data[buf >> 18] = buf >> 4;
      status |= 1 > 18);
      }


      The simple reason for that is that otherwise the kernel would be unpredictable.


      Point taken, but I hope you're open to the idea that C++ classes can be written that avoid these problems. In particular, it's relatively easy to define your own memory management scheme. This could be confusing to some (redefinition of new and delete would not be obvious in other parts of the code), but C++ has some nice features that facilitate scalability. I'm sure you'll agree that maintaining such a complicated thing as a cross-platform kernel can use some more sophisticated tools for software development than what C provides.

    7. Re:Progress by alienw · · Score: 1

      Yeah, who wants a common driver API for video, network, or sound cards...

      Why that requires C++ is beyond me.

      You can do some pretty neat things in C++ if you know what you are doing. If you don't know what you are doing, you can do some pretty crappy things.

      It's kinda hard to know what you're doing when the compiler generates megabytes of extra code. Ever try disassembling a program written in C++? Want to tell me you know exactly what the compiler will generate?

    8. Re:Progress by abdulla · · Score: 1

      I don't think this will be accepted in the kernel (and generally, I don't think it should be), but I can't wait for these improvements to trickle back in to G++ if possible. This'll be a great speed improvement and will squash all those anti-exception arguments that are mainly based around performance.

    9. Re:Progress by alienw · · Score: 1

      First, C is sufficiently low-level that it's possible to know exactly what machine instructions a compiler will generate. Second, if a kernel developer actually benefits from type checking, they should not be developing kernel code.

    10. Re:Progress by alienw · · Score: 1, Insightful

      Contrary to what you think, I _have_ read Linux kernel code. It's perfectly readable for a project of that magnitude. I don't know why you think it's obfuscated, I am sure the thousands of contributors would disagree with you on that one. Of course, it's not exactly a project for a beginning programmer -- DUH.

    11. Re:Progress by iabervon · · Score: 0

      C++ is not a well-designed language. There have been many occasions on which incompatible changes had to be made in the language standard. Unless you're actually doing language research, it's a good idea to avoid it.

      On the other hand, a good exception mechanism, if implemented in C, would be very useful in the kernel for error-handling.

      One of the main reasons for not supporting C++ in the kernel is that the kernel is object-oriented C, and C++ objects would confuse matters. Of course, C++ has other features as well, and it would be good if those, when useful, could also be supported in a standard idiom in C in the kernel.

    12. Re:Progress by Anonymous Coward · · Score: 0

      Yeah, who wants a common driver API for video, network, or sound cards...

      Apparently the Linux kernel developers don't. Becaues they make life harder for driver writers every day by constantly removing symbols, renaming functions, etc. etc. The kernel API isn't stable.

    13. Re:Progress by Anonymous Coward · · Score: 0

      C++ has only been unstable in the past, before it was seriously standardised.

    14. Re:Progress by 12357bd · · Score: 2, Informative

      Yes, a kernel is more difficult than a word processor, but that doesn't mean that implementors must implement stupid C++ code.

      No, the problem is not if it's difficult or not, is the fact that C++ implies the existence of an intrinsic memory management behaviour (new/delete), that is not really compatible with the strict memory management a kernel must implement.

      --
      What's in a sig?
    15. Re:Progress by alienw · · Score: 1

      Well, you got a point about drivers being pretty shitty, but the core kernel is not nearly as bad. Drivers pretty much have to meet one criterion, and that's not crashing the kernel TOO often. Especially something really obscure (what you are looking at is a driver for a Gravis gamepad that hasn't been made for about 5 years now). I wouldn't expect that driver to work, much less have the same coding standards as the rest of the kernel.

      I do realize you can work around many of the flaws in C++, but doing so is more complex than just sticking to C. I just don't think that kernel complexity is something that can be tackled with OOP. C++ is great for writing applications, but it was never intended for kernels. After all, there is a good reason why there are virtually no production-grade operating systems that actively use C++ for the kernel.

    16. Re:Progress by AaronW · · Score: 1

      I agree that C++ can be a good thing. A number of years ago I worked on an Asynchronous Transfer Mode (ATM) networking driver which included the full ATM stack and Lan Emulation. The whole driver, except for the lowest level base driver, was written entirely in C++. C++ kept the code simple and modular and cleaner than the equivalent C code. When I had to expand the LAN Emulation code to handle multiple ELANS, it took very little time, just changing a pointer to the LANE code to an array of pointers.

      I had to debug this code at the assembler level in many cases on the platform the code was written (OS/2), and I did not see any significant overhead caused by the use of C++. Then again, this was using the Watcom 16-bit C++ compiler and not G++. (Note: most OS/2 device drivers were 16-bit, even though the OS kernel was mostly 32-bits).

      Of course, the C++ data path code was written to be very flat without a lot of inheritance, no multiple inheritance, no templates, exception handling, etc., so as to be lean, fast and transparent. Other less performance critical code used more of the C++ features.

      At the same time we had another driver we worked on for Windows NT and Solaris which was written entirely in C. The C++ driver was 100K lines of code. The C driver was over 350K lines of code. The C++ driver was much smaller (binary) and faster, not to mention, it was far more stable and had more features. By using inheritance, the LANE code could emulate either Ethernet or Token Ring or both on a per-elan basis, with the particular network personality being subclassed from the main LANE class.

      Both drivers code bases were written to be quite portable as well.

      Usually when handling multiple devices you keep passing a pointer to a data structure for the device for each function. In C++, you can think of that as the this pointer in a class.

      There is no reason for C++ code to be slow if it is written with performance in mind.

      -Aaron

      --
      This post is encrypted twice with ROT-13. Documenting or attempting to crack this encryption is illegal.
    17. Re:Progress by geg81 · · Score: 5, Insightful

      The simple reason for that is that otherwise the kernel would be unpredictable.

      Complex code becomes predictable by building layered abstractions with well-defined interfaces. C++ supports that better than C.

      Let's say the error logging function used the string class (which likes to allocate memory behind your back).

      The kernel almost certainly wouldn't be using "the" string class, but its own string class, adapted specifically to the needs of the kernel. Right now, the C-based kernel doesn't use the user mode C library either, after all.

      If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash.

      Quite to the contrary. Not only would the kernel not crash, with a properly designed string class, out of memory conditions would actually be guaranteed to be handled correctly in all string operations everywhere in the kernel. No more case-by-case checking and handling of whether the memory allocation happened to succeed this time or not. In this particular case, the string class would throw an out-of-memory exception in the error handler and the stack would unwind up to the point where there is a handler.

      Furthermore, the error logging function can decide to intercept such exceptions and print an emergency error message on the console, and it can do so reliably without ever having to worry about checking a single status or return value.

      Altogether, this is a big improvement over C-based handling of such situations. But if you want to keep this situation from occurring in the first place, there is no more reason for the error logging function to allocate memory in C++ than there is for it to do so in C.

    18. Re:Progress by Bloater · · Score: 1

      The kernel developers normally care more about the fast path... use fewer cache lines, and quicker functions with fewer pipeline stalls. Exceptions are ideal for that, as it makes the error case slower than the C version (where the error case is about the same speed as the normal case), but the normal case can be made much faster depending on implementation.

    19. Re:Progress by Salamander · · Score: 2, Insightful

      It's not so much that C++ itself is so bloated etc. but that some of the common C++ programming idioms - full of templates, overloading, deeply nested class hierarchies with virtual methods, etc. - can lead to bloat. It's never good to have what looks like a simple assignment statement turn into thousands or even tens of thousands of instructions, but it's particularly dangerous in the kernel. Templates are particularly bad because they get re-instantiated for every type they're used with and that can very rapidly cause executable sizes to balloon out of control. They're a non-solution to a problem that's more than adequately solved by treating types as first-class objects, or by lower-level methods such as explicit dispatch-table pointers.

      Sure, you can tell your developers to use a subset of C++ that doesn't have such problems, but what's the point? Why pay the runtime-support and tools cost and require greater vigilance in code reviews just for some syntactic sugar (which is all that would be left)? I'm not absolutely opposed to using C++ in a kernel where it's already supported, but there are costs that would have to be justified compared to just using C.

      --
      Slashdot - News for Herds. Stuff that Splatters.
    20. Re:Progress by Anonymous Coward · · Score: 0
      No, the problem is not if it's difficult or not, is the fact that C++ implies the existence of an intrinsic memory management behaviour (new/delete)


      This is no more true than "C require malloc/delete." Nothing is required. I write C++ code all the time that does no runtime memory management, just as anyone could write C that doesn't use malloc/delete.

    21. Re:Progress by mikefe · · Score: 1

      They find problems and fix them and all other references to such code that is in the kernel tree.

      The only problem is if you don't have your code in the tree and if you don't that's your problem.

      Also, if you are doing any development, you know not to change your base often. That means if you are writing a large subsystem, you are not doing so on the latest kernel because you won't know what bugs are yours and which are introduced by the base kernel update.

      --
      There: Something at a specific location.
      Their: Owned by someone.
      Please make sure your english compiles.
    22. Re:Progress by Anonymous Coward · · Score: 0

      Now read that code again, imagining some of those '>>'s were overloaded to kalloc memory and have side effects and tell me what it does.

    23. Re:Progress by Deorus · · Score: 1, Flamebait

      > Yeah, who wants a common driver API for video, network, or sound cards...

      I don't understand why a common driver API is not possible to do in C... Would you care explaining?

      > Not to mention that drivers are all about abstracting the hardware and interface implementation from the OS itself anyway...

      Does that mean we should give up on transparency?

      > You can do some pretty neat things in C++ if you know what you are doing. If you don't know what you are doing, you can do some pretty crappy things.

      This (again) begs the question: what can you do in C++ that you can not do in C? Is it just because classes, objects, constructors, destructors, inheritance, and all that crappy OOP stuff is specificly declared that C++ is that superior? You can do pretty well the same in C! There is absolutely no consistent technical reason supporting the use of C++ in the Linux kernel!

      Quoting the FAQ that you should indeed read since there are some Linus quotes there:

      Should the kernel use object-oriented programming techniques? Actually, it already does. The VFS (Virtual Filesystem Switch) is a prime example of object-oriented programming techniques. There are objects with public and private data, methods and inheritance. This just happens to be written in C. Another example of object-oriented programming is Xt (the X Intrinsics Toolkit), also written in C. What's important about object-oriented programming is the techniques, not the languages used.
    24. Re:Progress by 12357bd · · Score: 1

      C++ code without objects?

      --
      What's in a sig?
    25. Re:Progress by fitten · · Score: 2, Insightful

      Yeah, who wants a common driver API for video, network, or sound cards...

      I don't understand why a common driver API is not possible to do in C... Would you care explaining?


      I didn't mention anything about choice of language. The OP didn't either.

      Not to mention that drivers are all about abstracting the hardware and interface implementation from the OS itself anyway...

      Does that mean we should give up on transparency?


      No, but I fail to see why the kernel would have to see into the details of how a device driver is implemented. As long as it conforms to a well defined interface, it shouldn't care at all how it is implemented.

      You can do some pretty neat things in C++ if you know what you are doing. If you don't know what you are doing, you can do some pretty crappy things.

      This (again) begs the question: what can you do in C++ that you can not do in C? Is it just because classes, objects, constructors, destructors, inheritance, and all that crappy OOP stuff is specificly declared that C++ is that superior? You can do pretty well the same in C! There is absolutely no consistent technical reason supporting the use of C++ in the Linux kernel!

      Quoting the FAQ [kernel.org] that you should indeed read since there are some Linus quotes there:




      I agree with that quote but it has nothing to do with the fact that Linus said it. (And it doesn't "beg the question" because that phrase means something else.)

      I've written OO code in C for the past 17 years or so as well as programmed in C++, Java, and C# (more recently) among other lesser known languages. I'm fully aware that I can do in C what C++ does, it just may take a bit more coding on my part to do some of the things. In fact, early C++ compilers were just manglers that output mangled C and compiled that for your program. With newer C++ standards, it isn't that easy anymore, though. Anyway, just as it was said in the quote that you posted, it isn't important what language you use, so what's with the beef against C++?

    26. Re:Progress by fitten · · Score: 1

      Correction, the OP mentioned C++ in the statement but in reference to common APIs and such that I inferred as I posted.

    27. Re:Progress by arkanes · · Score: 1
      Agreed that templates can do crazy things to your executable size. That said: ...because they get re-instantiated for every type they're used with
      This is not neccesarily true, although I don't know if any current C++ compiler manages this properly. Any way, it's not an inherent problem of templates.

      solved by treating types as first-class objects , or by lower-level methods such as explicit dispatch-table pointers.

      Templates are a compile time system. A template-based system is faster (modulo cache issues caused by bloated executables....) than a dispatch table because the type lookup isn't deferred until runtime.

    28. Re:Progress by tomstdenis · · Score: 1

      Yeah, who wants a common driver API for video, network, or sound cards...

      Um, there is no reason why you can't do this in C relatively easily. All you have todo is make a common API and stick to it.

      In my crypto library I have a dozen ciphers, hashes and prngs. Every cipher has the exact same function prototypes and can be called via a table driven system.

      "C++" effectively would do the EXACT SAME THING except with less control over the actual implementation.

      Tom

      --
      Someday, I'll have a real sig.
    29. Re:Progress by Anonymous Coward · · Score: 0
      C++ code without objects?


      Objects don't require new/delete. But yes, there are many features that C++ has that would be nice to use, even without objects. Deterministic finalization, for one. "Construction is resource allocation" is a fantastic way to prevent leaks of memory, handles, etc.
    30. Re:Progress by ucblockhead · · Score: 1, Informative
      The above C code can be deciphered simply by reading the code. Sure, it may be difficult because it isn't great code, but it can be done.

      On the other hand, if the above were C++ code, it could mean absolutely anything, depending on how operators were overloaded. Somebody could have defined "^" to play the star spangled banner on the system speaker for all you know. In C++, you can never really say for sure what anything means without looking in every single include file.

      --
      The cake is a pie
    31. Re:Progress by Deorus · · Score: 1

      > No, but I fail to see why the kernel would have to see into the details of how a device driver is implemented.

      First, because we are talking about a monolithic kernel in which if a driver poohes, the whole system poohes too, so it is a good idea to know what really poohed and why.

      Second, because the more abstract you make your API the less optimized and useful it will be (which for device drivers is not a Good Thing).

      Third, I don't really understand how this relates to the need for C++ on the kernel at all.

      > I didn't mention anything about choice of language. The OP didn't either.

      The whole story is about C++ on Linux, what are we talking about then?

      > what's with the beef against C++?

      First, it is not my problem if you haven't read the whole point on that FAQ, the story, or the article whatsoever.

      Second, you are the one defending the change, but you don't seem to come up with any reasonable technical argument to support that change. Do you expect everyone to jump in just because you though it would be better?

      For me it seems that the only useful thing that patch does is to add more useless code to the kernel.

    32. Re:Progress by gnuLNX · · Score: 1

      Sure. As long as I write the code I will tell you farily accuratly what will be produced...from gcc.

      --
      what?
    33. Re:Progress by Jeremi · · Score: 1
      First, C is sufficiently low-level that it's possible to know exactly what machine instructions a compiler will generate.


      If you need that much control over the code generated, nothing stops you from writing a C function to do it, or even an inline assembly function.


      Second, if a kernel developer actually benefits from type checking, they should not be developing kernel code


      By that logic, professional race drivers don't need to wear seat belts. Even the most seasoned programmer benefits from type checking -- everybody makes dumb mistakes occasionally, and it's much better to have them caught the next time you compile then spending hours trying to figure out why your kernel is crashing.

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    34. Re:Progress by strider44 · · Score: 1

      Just wondering, have you ever seen someone deliberately and seriously overload the ^ symbol to play the star spangled banner on the system speaker?

    35. Re:Progress by scotch · · Score: 1

      The philosophy behind is C++ is two fold. C++ provides for multi-paradigm programming. With C++, you don't pay for what you don't use.

      --
      XML causes global warming.
    36. Re:Progress by runderwo · · Score: 1

      I'd like you to show me an example of any CRC code that is remotely readable or intuitive to anyone but the author.

    37. Re:Progress by GenSolo · · Score: 2, Insightful

      On the other hand, if the above were C++ code, it could mean absolutely anything, depending on how operators were overloaded.
      Except that they can't be overloaded in that case as both operands are built-in types. You can't overload an operator unless at least one of the two operands is a user-defined type, which prevents people from making this do something unexpected. That is, you can't make operator^(int, int) play the star spangled banner, no matter how hard you try.

    38. Re:Progress by Anonymous Coward · · Score: 0

      Now that I can, you can be damn sure I will.

    39. Re:Progress by cheekyboy · · Score: 1

      Why dont you just ban #defines in C then, because you could just as easily make even more horrid wierd code in C using 100s of MACROs and enums.

      HELL, you could make your C code look just like wierd VB code using #defines.

      --
      Liberty freedom are no1, not dicks in suits.
    40. Re:Progress by Jugalator · · Score: 1

      In C++, you can never really say for sure what anything means without looking in every single include file.

      Unless the kernel team has rules in place saying how operator overloading is (or maybe is not) allowed.

      --
      Beware: In C++, your friends can see your privates!
    41. Re:Progress by akuma(x86) · · Score: 1

      How would c++ fix this code? It just looks like some bit twiddling. What this code needs are better variable names and more comments.

      Sometimes, device drivers need to push bits around in a very explicit and direct way since they're controlling hardware after all. You can layer abstractions on top of abstractions and interfaces but AT THE BOTTOM OF THE STACK, (ie - the kernel and drivers), you still need to push those bits around.

    42. Re:Progress by Anonymous Coward · · Score: 0

      I suggest you take a look at the specifications for the new and delete operators, including the placement new and delete operators. I'm not sure what strict memory management has to do with programming in C.

    43. Re:Progress by Mock · · Score: 1

      Score 5: Informative?
      Try score 0: troll.

      If you're going to argue that C++ is bad for the kernel because someone might use std:string, you might as well go all the way and say that C doesn't belong in the kernel because someone might use printf in the memory handlers.

      Just because the tool allows it doesn't mean it should be used in every application. After all, a kernel is much different from, say, a word processor.

    44. Re:Progress by ebbe11 · · Score: 1
      Nothing will come out of it, for the simple reason that C++ does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      Having used C++ for embedded real-time programming for over five years, I can say that this is absolutely untrue. You have to know what you are doing (as in "don't use libraries that do something behind your back") but programming in C instead of C++ does not give any advantages at all. I for one am not willing to downgrade to C if I can avoid it.

      Also, if abstractions and implementation hiding are detrimental to program design, we should all use assembly language. After all, optimizing compilers can't be trusted.

      --

      My opinion? See above.
    45. Re:Progress by dooglio · · Score: 1
      It's been pointed out before--you can do the same crap with macros. You can obfuscate the hell out of straight 'C'. I've spent more than my share of time debugging crap C code with monster switch statements spanning pages and pages of code with hundreds of variables. One small change and the house of cards comes tumbling down.

      Bad design happens no matter what language is chosen. :-)

    46. Re:Progress by ebbe11 · · Score: 1
      is the fact that C++ implies the existence of an intrinsic memory management behaviour (new/delete)

      C++ implies no such thing and if you'd ever used it seriously, you' know that.

      I have written loads of embedded realtime C++ code including code for a heart defibrillator where a half second delay may mean the difference between reviving a patient and killing him. And yes, if I were that patient, I'd gladly trust my life with that defibrillator.

      --

      My opinion? See above.
    47. Re:Progress by nihilogos · · Score: 1

      I think C++ has a real place in the kernel

      Just look at what it's done for the Windows kernels.

      --
      :wq
    48. Re:Progress by maxwell+demon · · Score: 2, Insightful
      Nothing will come out of it, for the simple reason that C++ does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

      Obviously, C does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the printf function (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

      I hope you get the point.
      --
      The Tao of math: The numbers you can count are not the real numbers.
    49. Re:Progress by Anonymous Coward · · Score: 0

      > > I didn't mention anything about choice of language. The OP didn't either.

      > The whole story is about C++ on Linux, what are we talking about then?

      Man, you're really a fan of selective quotation and MISSING THE FUCKING POINT, aren't you?

      The WHOLE FUCKING POINT of what he's saying is that the Linux kernel ALREADY CONTAINS ABSTRACTIONS. In C. That is, Linus Torvalds thinks abstraction is a good thing in his Linux kernel. Since you were arguing that C++ was bad because it introduced abstraction, this fact is relevant to those trying to point out to you what an idiot you are.

      Go back and try actually READING the posts you're replying to. It may help to get someone to hold your knees down as you do so, as you seem to have a jerkiness issue down there.

    50. Re:Progress by Anonymous Coward · · Score: 0

      Second, if a kernel developer actually benefits from type checking, they should not be developing kernel code.

      You don't hear many generals saying "if a soldier actually benefits from having a safety catch on his gun, he should not be in the army". In fact, I do believe the US army actually encourages its troops to keep the safety catch on when they're not in a combat zone.

      Man, am I glad you don't run the army.

    51. Re:Progress by Anonymous Coward · · Score: 0
      The following line looked suspicious to me:
      status |= 1 > 18);

      In the grip.c file of linux 2.4.26 I found a more plausible one:
      status |= 1 << (buf >> 18);
    52. Re:Progress by iGN97 · · Score: 1

      The argument about operator overloading introducing overwhelming uncertainty is getting worn. The "somebody" that made operator^ play the star spangled banner would probably, in the context of most projects, be someone you could reach out and slap, if not yourself. Incredible amounts of sense is delivered in a slap. This person would not do this again.

      Someone could easily make a "void clearscreen()" play the same song. They would deserve to be slapped too.

      Any decent C++-coder will know when operator^ is called. If not, they will find out when the song starts.

    53. Re:Progress by Anonymous Coward · · Score: 0

      I am sorry but I won't keep commenting on this thread, it's pointless, has gone too far, and I'm too lazy and too tired to explain my point, plus I don't think it's worth it, maybe another day. I agree with you that I've missed some points in this thread, but you are also getting me wrong.

      After replying this thread, I'm coming to believe that this is really true. I wasn't aware of how true that comment was until today. By the way: is it just me or you seem a little bit nervous? Get some days off Slashdot, these things are not good for your psychological health, you know? Don't take this too seriously or personally, it's just a public forum on the Internet.

      -- Deorus

    54. Re:Progress by fitten · · Score: 1

      "C++" effectively would do the EXACT SAME THING except with less control over the actual implementation.

      Yup, the only (potential) difference is that a bunch of the stuff you have to do manually in C (table driven system, for example) will be done by the compiler for you in C++ (vtable).

      The only real discussion point here is that the "less control over the actual implementation" means that in C, you are writing what C++ does for you in a number of cases. Not all of it complex, but maintaining your table by hand is more error prone than trusting the compiler to do it for you in some cases.

      As I said before, I've had to use C for the past year or so on a project (no choice) and many of the things I've implemented are just things that C++ does for you automagically, basically exactly the same things that you're talking about. before that, I worked for five years on a similar system written in C but basically reimplementing stuff that C++ does for you because the writers all "knew" that C++ was evil (mostly due to some bad experiences they had because they didn't know enough about C++ do avoid some of the common performance mistakes and they had used C++ back when it was relatively new and was still sorta buggy and kludgy). That didn't stop them from implementing exactly what C++ does for you though. They just felt more secure doing it all by hand rather than letting the compiler do it for them. /shrug

    55. Re:Progress by sir99 · · Score: 1

      By your argument, Linus is unfit to develop the Linux kernel. In case you haven't noticed, Linus has been adding lots of type annotations above and beyond what C supports, and checking them with the semantic analyzer he wrote. Not only that, but it's caught lots of errors, so apparently he's not the only unfit kernel developer.

      --
      The ocean parts and the meteors come down
      Laid out in amber, baby.
    56. Re:Progress by ucblockhead · · Score: 1

      Yes, but looking at a code snippet, how do you know those are ints?

      --
      The cake is a pie
    57. Re:Progress by Anonymous Coward · · Score: 0

      If you can't be bothered to look at the declaration in the same file to find the datatype, I can't help you. To be honest, I know that they're ints because it's C and you can't overload the operators in C, but were it C++, I'd check the declaration of the variable if the type wasn't obvious.

    58. Re:Progress by p3d0 · · Score: 1
      In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.
      This argument suffers from a common misconception: that "information hiding" means hiding information from developers. It doesn't. It means hiding information in one software module from another.

      Abstractions are not inherently opposed to what you're referring to as "transparency". Good abstractions don't harm transparency, and actually make code clearer by clearly defining the interactions between modules.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    59. Re:Progress by alienw · · Score: 1

      Since when is 1/2 second real time? Real-time means millisecond to microsecond resolution, and even C is often too high-level for truly real-time systems. Usually that type of stuff is coded in assembler, where you can predict exactly how much time any given instruction will take. Of course, that does require a more skilled programmer.

    60. Re:Progress by Anonymous Coward · · Score: 0

      Or use hungarian notation, if you're too lazy to do that.

    61. Re:Progress by grmoc · · Score: 1


      BS.

      Even assembly is not necessarily deterministic, depending on the system. For instance, you may have a problem with locking the memory bus on a multi-cpu system which would increase the latency of that memory instruction by an unknown amount.

      The definition of 'real-time' is always fluxuating. The best definition that I've been able to find is 'hard-real-time==system calls are guaranteed to complete in a pre-specified amount of time,' i.e. that there is some (hopefully large) amount of determinism in the system, and the program is able to utilize that to make itself deterministic.

      C code will have the same level of determinism as assembly, or c++, or any other compiled language (assuming you're using the same compiler and compiler flags).

      In constrast, here is an analogy to your argument, using binary==assembly, assembly=C++/C

      Using your argument, you should forgo the use of assembly-- its too high level. That blasted assembler may do some translations to/on what you inputted! If you really wanted it to be real-time you should program in binary! ... that doesn't make sense (to me)...

      You can examine the assembled output of the C or C++ compiler to understand the instruction count, just as you can count the assembly instructions in the assembler. You've simply used a different (and arguably better) too to generate the assembly.

    62. Re:Progress by alienw · · Score: 1

      Even assembly is not necessarily deterministic, depending on the system

      Then it's not a real-time system! Hard real-time systems should always be deterministic.

      Any system has some degree of determinism. It's just that a hard real-time system needs to guarantee that the required tasks will be completed in the required amount of time. It's not possible to guarantee that the tasks will be completed if your processor does not have a strict upper bound on the amount of time any given instruction will take.

      If you want to code a real-time app in C++, you will pretty much have to disassemble your program afterwards to make sure the compiler didn't do something stupid. That's rather difficult, so hardly anybody does it. Unlike an assembler or a C compiler, a C++ program does not easily translate directly to assembly, and the compiler generates thousands of instructions (various virtual function tables, default constructors, default destructors, and other shit). If you are telling me you can actually work through that with a disassembler, try it sometime. In any program that uses stuff like inheritance, it's damn near impossible to figure out what's going on, much less verify correctness.

      Besides, C++ doesn't work at all for things like DSPs and Harvard architecture 8-bit microcontrollers (which is what's used in about 80-90% of the real-time systems out there). They usually have less than a kilobyte of RAM. Assembly and C work very well for these architectures.

    63. Re:Progress by Lars+T. · · Score: 1
      C++ is not a well-designed language.

      As opposed to C? Remember, C++ is supposed to make a well-designed language out of C. And don't pretend signed char is a byte.

      --

      Lars T.

      To the guy who modded me down from perfect to terrible Karma - Apple haters still suck

  16. Sorry to break it to you... by RAMMS+EIN · · Score: 2, Informative

    Linux doesn't want any C++, so as long as he's at the top, it likely won't get far. And I think that's good, given the state of C++ in gcc (hint: slow and memory-intensive compiles, generating subobtimal code).

    But I'll shut up. I've pretty much turned my back on C and C++ anyway.

    --
    Please correct me if I got my facts wrong.
    1. Re:Sorry to break it to you... by Anonymous Coward · · Score: 1, Insightful

      lol. One day he'll use C++, and then we'll see what happens to the kernel.

      He sure as hell isn't going to start writing the kernel using Java now is he!

    2. Re:Sorry to break it to you... by Anonymous Coward · · Score: 2, Funny

      Hello.

      My name is Linux Torvalds, and I pronounce "Linus" "Linus".

    3. Re:Sorry to break it to you... by Anonymous Coward · · Score: 0

      Umm, how is this a troll?

  17. Who cares? by Percy_Blakeney · · Score: 5, Informative
    I really don't see the use in porting these features to the Linux kernel -- they'll never be used in any mainstream kernel release. Linus has stated many times that he doesn't particularly care for C++ in the kernel:

    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).

    1. Re:Who cares? by Kethinov · · Score: 2, Interesting

      I agree entirely. C++ in the Linux kernel is a largely bad idea.

      I am all for the kernel remaining C forever, but just for the sake of curiosity's fancies, I wonder how much better Objective-C would be as a high level yet still high performance solution as opposed to the messier C++?

      --
      You're right, I wouldn't steal a car. But if it were possible, I sure as hell would download one!
    2. Re:Who cares? by Lally+Singh · · Score: 1

      Hmm, so, was there ever an explanation to these?

      the first arg has no explanation.
      the second -- what hidden memory allocations??
      third: you can write in ASM too, but that doesn't mean you should.

      --
      Care about electronic freedom? Consider donating to the EFF!
    3. Re:Who cares? by Anonymous Coward · · Score: 1, Interesting

      Fact is, its harder to write robust code in C than it is in C++.
      Fact is, we ain't in 1992 anymore. Our computers can take the miniscule slowdown compared to the better code.

      His point 1 is unproven.
      His point 2 is wtc? Was he thinking Java here?
      His point 3 has minimal validity; but still has lots of unproven sitting behind it.

      His point (a) is bigoted.
      His point (b) is bigoted.
      His point (c) is asinine.

      Haha! Now I'm a troll for dissing Linus!

    4. Re:Who cares? by pyrrho · · Score: 1

      memory behind your back... not really, you can

      (0) on exception: sure, don't use C++ exceptions in the kernel. no need.

      (1) control the allocation or even, gasp, not use classes, which are just one idiom available in C++.

      (2) re: writing in C anyway, C/C++... yes, why not use C++ as a better C... or is the "const" keyword evil.

      A C bigot... perhaps?

      --

      -pyrrho

    5. Re:Who cares? by homebrewmike · · Score: 2

      Alternatively, someone could try the patch, and re-evaluate it.

      Computer Science isn't a religion, it's evolutionary. If the "C++ patch" works great, and makes things easier, so be it. If not, it gets tossed out.

      If it is good, and it is rejected, then what's the point of Open Source?

    6. Re:Who cares? by dingbatdr · · Score: 0

      Computer science isn't religion? Clearly you have never gotten in the middle of a emacs-vs.-vi flamewar.

      dtg

      --
      The truth is an offense, but not a sin.------R. N. Marley
    7. Re:Who cares? by abdulla · · Score: 1, Funny

      (d) Profit!??

    8. Re:Who cares? by AuMatar · · Score: 5, Informative

      The first argument is easy- exceptions are a Bad Idea. Error codes are much cleaner and more logical. Even the few embedded projects I know that use C++ outlaw the use of exceptions in their code (generally templates as well, for emmory reasons).

      The second- C++ has hidden allocations all over. In C, its easy to find memory allocations. Grep for malloc (or kmalloc in the kernel). In C++, you have temporary objects being instantiated all over the place, automatic constructors/destructors being called, etc. Its nowhere near as open or easy to find (especially temporary object creation. If you don't think thats a problem- try putting a cout statement in a constructor, and write a function that takes an object as a parameter and returns that object. Count how many you see. Its more than 1.) Its not as clean. While this may be tolerated (although confusing) for an application, for a kernel its murder. Memory is tight, and mallocing will kill you performance wise if you need to grab a new free page. It may not even be possible to do if interrupts are locked. Its a hassle.

      In fact, a lot of embedded project don't even allow dynamic memory. I design printer firmware. We are not allowed to call malloc. All memory is tightly controlled by thesystem and is strictly deterministic to ensure we can always do a job. A large amount of object creation doesn't make sense in an embedded/kernel environment.

      Third- why not? There's places where its the best tool fro the job. Assembly gets a bad rap, really its a nice simple language. The real question is- what does C++ give you that C doesn't? Objects- C has them. Inheretance? Very rarely does it really benefit you, its usually used because "we're OO, we're supposed to use it". Templates? Ok, those can be useful for things like linked lists, although the STL goes way over the top with it. Exceptions? See above. The gains of C++ are minimal, the pain of it is large.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    9. Re:Who cares? by Anonymous Coward · · Score: 0

      If it is good, and it is rejected, then what's the point of Open Source?

      1. He had access to the source to be able to do this.

      2. He is free to use it however he wants.

      3. Others are free to join the project and take it where ever they so please.

      5. You're an idiot.

    10. Re:Who cares? by KAMiKAZOW · · Score: 1

      "OpenBFS, as all file systems under BeOS, is being developed as a kernel add-on. Unlike all other file systems (and kernel add-ons in general), it is being developed in C++. Contrary to popular belief, it is possible to use C++ in the kernel"

    11. Re:Who cares? by Percy_Blakeney · · Score: 1
      Hmm, so, was there ever an explanation to these?

      Search Google or the kernel mailing list for "C++" and you'll come up with discussions about the whole issue. For example, see this discussion from earlier this year (which includes the quote from Linus.)

      third: you can write in ASM too, but that doesn't mean you should.

      No, that's not true -- sometimes, you really need to use ASM. Go poking around the linux kernel (in particular, the 'arch' subdirectory) and you'll find plenty of assembly code. The point here is that you use the right tool for the right job. Linus, obviously, feels that C is the better tool for writing an operating system kernel than C++. Obviously, there's more than one way to do things, but I tend to respect Linus' opinion on something like this.

      Of course, if anyone feels like Linus is a total idiot, then they can try porting Linux to C++. I'm willing to bet that if someone could show substantial real benefits from a C++ Linux, Linus would happily eat his words.

    12. Re:Who cares? by Anonymous Coward · · Score: 0

      > His point (c) is asinine.

      yet true in this case...

    13. Re:Who cares? by Anonymous Coward · · Score: 0

      dude i am willing to bet you my tonka trucks that its a C kernel module talking to some C++ residing some where else ...

      get a clue!

    14. Re:Who cares? by Hanji · · Score: 1

      Objective-C is awesome, but it's not appropriate for very high-performance systems; Its message-passing architecture entails significant overhead on method ("selector") calls, even compared to virtual methods in C++.

      At least, so is my understanding. Correct me if I'm wrong.

      --
      A Minesweeper clone that doesn't suck
    15. Re:Who cares? by slashdot.org · · Score: 5, Insightful

      Boy oh boy, where do we start.

      Please people, I know Linus is God, and I have a lot of respect for the man. But I don't care who it is, if people make statements like this, I'd like to see some back up.

      It sucks. Trust me - writing kernel code in C++ is a BLOODY STUPID IDEA.

      When someone says 'trust me' it either means "I'm too lazy to explain" or "I haven't really got something to prove it".

      The fact is, C++ compilers are not trustworthy. They were even worse in 1992, but some fundamental facts haven't changed:

      Well, I don't want to start a flamewar here, but while this may be true for the GNU compiler, it certainly is NOT true for, for example, the Microsoft compiler. (I know, how dare I say that...) It has produced code from C++ source for a _very_ long time and even the optimizer works very well.

      * the whole C++ exception handling thing is fundamentally broken.

      Why?

      It's _especially_ broken for kernels.

      Why? Maybe for the Linux kernel, because it wasn't designed with C++ exceptions in mind. And I'm not even say that that's bad, but why is it in gerenal broken for kernels?

      * any compiler or language that likes to hide things like memory allocations behind your back just isn't a good choice for a kernel.

      Well, that's really implementation and as such is your choice, it's not the language. Furthermore, no-one forces you to use _all_ possible language features. I personally stay away from many C++ language features such as overloaded operators.

      * you can write object-oriented code (useful for filesystems etc) in C, _without_ the crap that is C++.

      But why would you if you can do it cleaner in C++ and have the compiler generate the same quality code? What is crap about C++?

      What Linus needs to do is go back to the old days where he looked at assembly output. I still do that and have compared C++ with C many times and I can't see why anyone would not use C++.

      You don't have to use all the bells and whistles, shit, you can write plain ANSI-C and still use a C++ compiler for it's superior type checking etc.

      Anyways, to each his own, I guess...

    16. Re:Who cares? by Anonymous Coward · · Score: 0

      1) Outlaw templates for memory reasons? Could you please tell me what exactly templates have to with runtime (and so with memory requirements)? I tell you: nothing. They are just rules for generating code. They may slow down compilation and increase memory requirements of the compiler only.

      2) You may be surprised, but C++ _never_ allocates memory itself. Never. At all. It calls user defined operator new for it. Default one is in runtime library, and it calls malloc in many of the implementations. In fact, it's quite possible to use ANY memory management scheme in C++. You don't have to use the runtime library heap.

      I suppose you have never used C++ in any large project. It's a _very_ complicated and cumbersome language, it's 10 times more complicated than it should be, but it's _very_ powerful and flexible. And there is not a single feature in it which comes at any significant runtime performance cost.

    17. Re:Who cares? by Foolhardy · · Score: 5, Insightful
      This may not be the original intent of the article, but C++ does have features that C doesn't that won't cause any of these problems. It is better to attack specific features that are likely to be problematic instead of the entire language.

      Don't like exceptions? Don't use them. C++ doesn't require you to. Personally, I don't use them unless I have to interface with other code that does. I usually compile with exception support off.

      Is allocating memory in a constructor likely to cause problems? Make it a standard code practice for your project to never cause non-explicit memory allocation. Destructors can be forced to run at a specific time with delete or by using forced scopes (use {} around the lifetime of the local var). Copying objects in a standard way is easy to do, espescially if you always pass classes (structs) as references or by pointer.
      Memory is tight, and mallocing will kill you performance wise if you need to grab a new free page. It may not even be possible to do if interrupts are locked. Its a hassle.
      Are you saying that C++ always uses more memory than C? That's silly. If you can't call memory allocation functions right now, then allocate things on the stack. Make sure that the objects you create and the functions you call don't alloc either. You would have to make sure the functions were safe in C too.
      In fact, a lot of embedded project don't even allow dynamic memory. I design printer firmware. We are not allowed to call malloc. All memory is tightly controlled by thesystem and is strictly deterministic to ensure we can always do a job. A large amount of object creation doesn't make sense in an embedded/kernel environment.
      Ok, so don't use the heap. There is no reason that C++ needs to use the heap; everything can be allocated on the stack. Just like C.
      Third- why not? There's places where its the best tool fro the job. Assembly gets a bad rap, really its a nice simple language. The real question is- what does C++ give you that C doesn't? Objects- C has them. Inheretance? Very rarely does it really benefit you, its usually used because "we're OO, we're supposed to use it". Templates? Ok, those can be useful for things like linked lists, although the STL goes way over the top with it. Exceptions? See above. The gains of C++ are minimal, the pain of it is large.
      Assembly isn't too nice if you care about portability. It also depends on the architecture about how nice and simple it is. Segmented memory in assembly can be a nightmare.

      Don't use the STL implementation of linked lists if you don't like it. Done properly, you could use templates for even more than that, like different index sizes for a filesystem; a 32 bit version for small volumes, a 64 for large volumes and a 128 for extremely large volumes. Since there is no primitive 128 bit type, C++ lets you override operators to create a new type that acts exactly like a primitive. This word size would be a template parameter of the filesystem class; a static version created for 32, 48, 64 and 128 bit or whatever. One code set, no redundancy. Remember the Sun story about a 128 bit filesystem? It could be as easy as recompilation!

      How about namespaces? These would be very useful in the kernel, IMHO.
      Member functions are nice for associating a function with an object.
      Private data members allow you to put data in a structure that outside code doesn't need to know about so you can change it later without breaking compatibility. Documentation can do it too, but this can enforce it.
      I bet there could be some good uses for smart pointers.

      The fact that a language has a feature does not obligate you to use it. You can use code standards in your project that set sane regulations for the code in the project. You need standards for any a sizable project in ANY language, including C. I'm sure that the Linux kernel already has rules as to naming conventions, header file control etc... More could be created to regulate good usage of C++ in a kernel environment.
    18. Re:Who cares? by BCoates · · Score: 1

      Those aren't hidden malloc()s. those temporary objects are being constructed on the stack, and the constructor wouldn't have any overhead at all if you weren't putting a cout in there... unless you're writing objects that are expensive to copy-construct and passing them around in ways that get them copied, in which case "don't do that".

    19. Re:Who cares? by BCoates · · Score: 1

      1) Outlaw templates for memory reasons? Could you please tell me what exactly templates have to with runtime (and so with memory requirements)? I tell you: nothing. They are just rules for generating code. They may slow down compilation and increase memory requirements of the compiler only.

      In practice, templates can result in redundant code being produced and increasing the size of the executable's image by quite a bit. Theoretically better compilers and/or more carefully written tempate code could fix this.

    20. Re:Who cares? by Anonymous+Brave+Guy · · Score: 1
      The first argument is easy- exceptions are a Bad Idea. Error codes are much cleaner and more logical.

      <sarcasm> Of course, because cluttering four layers of code between detecting the error and reacting to it with maintenance hazards like forwarded return codes is a much cleaner approach than the two lines required to throw and catch an exception. </sarcasm>

      Even the few embedded projects I know that use C++ outlaw the use of exceptions in their code (generally templates as well, for emmory reasons).

      You do know that the templates hogging memory thing is mostly a myth, right? This sort of talk is put around by critics either who have no idea what they're talking about or who haven't thought through the way they are used in practice. Clearly and objectively, there is no merit to the argument, and I don't care how many people you cite who've worked on embedded projects (or for that matter popular free OS kernels) and say differently.

      C++ has hidden allocations all over. In C, its easy to find memory allocations. Grep for malloc (or kmalloc in the kernel).

      Except that you forgot automatic variables and information on the stack due to function call/return overheads, for a start. If you don't think they matter, try working on a project with really large data sets and recursive algorithms (or rather, their iterative equivalents, since the simple act of making a function call can become a liability in such an environment).

      In C++, you have temporary objects being instantiated all over the place, automatic constructors/destructors being called, etc.

      Sure, and anyone competent to write a kernel in the first place is going to learn the rules for how that happens in no time. There's no magic. It's not done behind your back. The rules are clear. The allocations may not be explicit, but in most cases that's just one less thing for the programmer to worry about. (On the other hand, maybe garbage collection doesn't prevent bugs in the real world, high level languages should all do away with their logical models and provide hacky low-level interfaces instead, and manual memory management is really the key to bug free code after all.)

      While this may be tolerated (although confusing) for an application, for a kernel its murder. Memory is tight, and mallocing will kill you performance wise if you need to grab a new free page.

      Fortunately for us, none of the implicit allocations you dislike so much normally uses malloc, and they're typically very efficient. And of course, in C++ you can replace things like the new operator for specific types if, when you write those types, you can identify a superior memory model, all without troubling the allocating code.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    21. Re:Who cares? by AuMatar · · Score: 1

      1)Templates cause greater code size than other methods (void*). Code size is just as important as ram- I had to cut 3K yesterday to fit in a 2 meg part, or we'd have lost a few hundred thousand dollars.

      2)Memory on the stack is still memory. And it can still kill you. And if those temporary objects you don't know are being created call new to create buffers, it will *really* kill you.

      I have used C++ in a large project. Its an overly complex language. A fewof the features are going the right way (I'd use templates in a non-embedded app), but its way too non-deterministic for embedded and kernel programming. And a lot of the features it has over C cause way more confusion, maintenance hassles, and performance hits than their worth.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    22. Re:Who cares? by Progoth · · Score: 1

      try putting a cout statement in a constructor, and write a function that takes an object as a parameter and returns that object. Count how many you see. Its more than 1.

      I read this, realized you must have done this, realized you don't know the first thing about C++, and realized I should stop reading.

      So I did.

      (if you care to know why, look up references (&), and while you're at it learn about const.)

    23. Re:Who cares? by AuMatar · · Score: 2, Insightful
      Yes, you can use C++ and outlaw features. The problem is getting everyone to agree not to use them. You then get people using them anyway and need to start rejecting patches. A few will manage to sneak in wthout noticing, and people will use that as an excuse to use it more. Been there, done that on a proprietary codebase. Its better just not to use C++.

      Are you saying that C++ always uses more memory than C? That's silly. If you can't call memory allocation functions right now, then allocate things on the stack. Make sure that the objects you create and the functions you call don't alloc either. You would have to make sure the functions were safe in C too.


      Read Meyer's "Effective C++" and "More Effective C++". There's a lot of hidden object creation that goes on. These take memory. If they malloc memory in constructors, they use LOTS of memory.

      How about namespaces? These would be very useful in the kernel, IMHO.


      Ok, syntactic sugar, but not a bad one. Of course, you could just have a naming convention, and you would likely get as much compliance there as you will with namespaces.

      Member functions are nice for associating a function with an object.


      We have that. Function pointers. Kernel uses them all over.

      Private data members allow you to put data in a structure that outside code doesn't need to know about so you can change it later without breaking compatibility.


      Static data variables do the same thing for single instance. For multi instance hold a pointer to a block of data, hold it in an integer, and call it a handle. Don't let the other guy see the implementation of the block.

      The problem goes back to the top- you're hoping that you can get hundreds of developers with no central control to follow a bunch of rules. They won't. They don't on propriatary projects when they're being paid to do so. On an open source project, it'll be worse. Its easier just not to use C++ than to say "Use C++ but not features x,y, and z".
      --
      I still have more fans than freaks. WTF is wrong with you people?
    24. Re:Who cares? by AuMatar · · Score: 1

      Easier said than done. Do you know every way an object can get copied? Some of them are VERY non-inutitive. I won't even pretend to know all of them, and I know some odd ones.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    25. Re:Who cares? by AuMatar · · Score: 1
      Of course, because cluttering four layers of code between detecting the error and reacting to it with maintenance hazards like forwarded return codes is a much cleaner approach than the two lines required to throw and catch an exception.


      Ah yes. Because its so much better to have a random error pop up 3 levels above the thing that cause it with an error identifier mapping to an API the handler didn't even know existed. Thats sooooo much cleaner

      You do know that the templates hogging memory thing is mostly a myth, right?


      No, it isn't. A good compiler will minimze it, but it exists. Say we have a linked list template. The code for just an int may take 12K (number pulled out of my ass). If you need to support a 64 bit int as well, it may now take 20K (some is reusbale). Adding in 16 bit is up to 28K. Using a void* for it all would stick with just the original 12K. On an embedded or OS, 8K is fucking huge.

      Sure, and anyone competent to write a kernel in the first place is going to learn the rules for how that happens in no time. There's no magic. It's not done behind your back. The rules are clear.


      No, they aren't clear. And they're frequently compiler dependant. Take this for example:

      class X{...}

      func blah(X x){
      X retval ...
      return retval
      }

      How many times is X's constructor called? Hint: it isn't 2. On some compilers its 3, on one I got 4. If that constructor calls malloc....

      you can replace things like the new operator for specific types if, when you write those types, you can identify a superior memory model, all without troubling the allocating code.


      Its not the method, I assume malloc is well tuned. Its the fact that its requesting memory at all. If the OS would need to walk the free page list to satisfy the request (or worse- page memory), thats a huge performance hit. No amount of tuning will make X bytes take less than that.
      --
      I still have more fans than freaks. WTF is wrong with you people?
    26. Re:Who cares? by AuMatar · · Score: 1

      Yes- because everyone always uses & and const correctly, right? Bullshit. Most C++ developers don't know what the difference between a reference and a normal variable is, much less declare everything they need to const. Not that I blame them ont he second- keeping track of what needs to be or can be const is annoying as hell, and you're bound to fuck it up so many times you give up.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    27. Re:Who cares? by tyrione · · Score: 1

      XNU Kernel has Objective-C in it as well as Objective-C++ ala I/O Kit. http://developer.apple.com/documentation/Darwin/Co nceptual/KernelProgramming/KernelProgramming.pdf

    28. Re:Who cares? by Foolhardy · · Score: 1
      Read Meyer's "Effective C++" and "More Effective C++". There's a lot of hidden object creation that goes on. These take memory. If they malloc memory in constructors, they use LOTS of memory.
      Care to cite specific examples where C++ the language itself causes hidden memory allocation? I'm not talking about libraries, but the language. You can use libraries that don't do that. Libraries that do bad things behind the scenes are as big a risk in C as they are in C++.
      Member functions are nice for associating a function with an object.
      We have that. Function pointers. Kernel uses them all over.
      I'm saying to use member functions for the orginazation they provide. You could get somthing similar with a good naming convention. This OTOH is supported by the language.
      Static data variables do the same thing for single instance. For multi instance hold a pointer to a block of data, hold it in an integer, and call it a handle. Don't let the other guy see the implementation of the block.
      Handles are more difficult to implement than simple pointers. You can't go from a pointer system with all public vars to a handle system very easily, whereas you can add private members to an existing structure easily.
      The problem goes back to the top- you're hoping that you can get hundreds of developers with no central control to follow a bunch of rules. They won't. They don't on propriatary projects when they're being paid to do so. On an open source project, it'll be worse. Its easier just not to use C++ than to say "Use C++ but not features x,y, and z".
      The Linux kernel has an official distrobution and it has central control. I hear about kernel patches all the time that don't get accepted into the main codebase.

      Having developers that don't follow rules and write sloppy code is a much bigger problem than a change of language can fix. Bad developers will write bad code no matter the language. There are plenty of rules you can break to make bad code in C too. There are plenty of rules in kernel code that bad developers will break, too. I can't imagine that C++ would make that big a difference; there will still be programmers that disregard the rules.
    29. Re:Who cares? by Anonymous Coward · · Score: 0

      Didn't BeOS use C++? Say what you will about it as a system, but it was NOT slow or bloated. That doesn't justify switching 3+ million lines of code to a new language, but to say that C++ is inherently unsuited to kernel work is fatuous.

    30. Re:Who cares? by AuMatar · · Score: 2, Insightful
      Care to cite specific examples where C++ the language itself causes hidden memory allocation? I'm not talking about libraries, but the language. You can use libraries that don't do that. Libraries that do bad things behind the scenes are as big a risk in C as they are in C++.


      Temporary objects. Compilers create temporary objects, especiall arounjd function calls/returns. These call the constructor, which may call malloc. The number of situations temporary objects can be made is actually failry high and very complex. If the language is creating objects you don't explicitly ask for and calling malloc off that, I count that as the language using memory. Its the fault of the language for creating the object.

      I'm saying to use member functions for the orginazation they provide. You could get somthing similar with a good naming convention. This OTOH is supported by the language.

      Like I said- function pointers. Like this:

      struct foo{
      int (*bar)(int);
      }

      foo has a member bar, which is a pointer to a function that takes an integer and returns an integer. You assign it like: foo->bar=myfunc; This is exactly what a member function does- the only difference is that the this pointer won't exist, so the first parameter to any member function would have to be a pointer to itself. You can even call it this :)

      Handles are more difficult to implement than simple pointers. You can't go from a pointer system with all public vars to a handle system very easily, whereas you can add private members to an existing structure easily.


      No they aren't. Its 1 line of code per function. Its like this:

      struct outer{
      int handle;
      }

      struct inner{
      int x,y;
      }

      int some_privlidged_func(outer *o){
      inner *in= (inner*)o->handle; //now just reference inner->x and inner->y
      }

      Having developers that don't follow rules and write sloppy code is a much bigger problem than a change of language can fix. Bad developers will write bad code no matter the language. There are plenty of rules you can break to make bad code in C too. There are plenty of rules in kernel code that bad developers will break, too. I can't imagine that C++ would make that big a difference; there will still be programmers that disregard the rules.


      It gives them additional ways to break the rules. The more rules, the more people will want to break them, or just waste your time disagreeing with them. Its a social problem, not a technical one. And with larger teams, its a larger problem (with small teams the team probably made the rules themselves and hashed out differnces then). On a small 3-5 person project restricting features works. On large ones it just becomes a hassle. On very large ones with more than 1 gatekeeper to the code, it breaks down entirely (all you need is 1 lazy/disagreeing member with check in privlidges).

      --
      I still have more fans than freaks. WTF is wrong with you people?
    31. Re:Who cares? by Pseudonym · · Score: 2, Insightful
      Of course, if anyone feels like Linus is a total idiot, then they can try porting Linux to C++. I'm willing to bet that if someone could show substantial real benefits from a C++ Linux, Linus would happily eat his words.

      This, of course, the wrong end of the proverbial stick. The benefit of C++ is that it lets you do pretty much what the kernel does now, only in a way that's easier to understand and more maintainable.

      To get any substantial benefit for existing code, you'd need to translate the entire kernel into idiomatic C++, which is a huge task. For new code, OTOH, C++ compatability should be a win. Unfortunately, the only way to prove this is to a) support C++, b) implement the new code twice, once in C++ and once in C, and c) compare them.

      Given that almost nobody is willing to implement their new feature twice just to prove a point...

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
    32. Re:Who cares? by Anonymous+Brave+Guy · · Score: 1
      Because its so much better to have a random error pop up 3 levels above the thing that cause it with an error identifier mapping to an API the handler didn't even know existed. Thats sooooo much cleaner

      The problem is exactly analogous to failing to forward a return code in a non-exception-based system, except that there's only one opportunity to forget with exceptions, it will usually be immediately obvious in testing if you do, and most decent debuggers can break immediately on an unhandled exception.

      Say we have a linked list template. The code for just an int may take 12K (number pulled out of my ass). If you need to support a 64 bit int as well, it may now take 20K (some is reusbale). Adding in 16 bit is up to 28K. Using a void* for it all would stick with just the original 12K. On an embedded or OS, 8K is fucking huge.

      OK, firstly you picked a bad example; it's routine in template code to use a void* based trick to avoid the overhead in that case. This is in chapter 1 of the newbie guide.

      Secondly, I call bullshit on your claim that 8K is "fucking huge" in embedded developments. I've worked in mobile telecomms, instrument control for engineering hardware, and God knows how many other embedded/firmware-related projects in my time. Not much this side of 1990 cares about that sort of memory limit. I'm sure there are a few cases around where it really still matters, but it certainly isn't the norm today, and where it is, you certainly aren't using a compiler that can take 8K to hold the code for a trivial linked list anyway.

      Take this for example:
      class X{...}

      func blah(X x){
      X retval ...
      return retval
      }
      How many times is X's constructor called? Hint: it isn't 2. On some compilers its 3, on one I got 4. If that constructor calls malloc....

      Leaving aside the fact that what you wrote doesn't make sense in any language I know, which constructor are you talking about? You potentially have a copy constructor call on the entry to the function (pass-by-value), a default constructor call on the first line (automatic variable) assuming you didn't pass it any parameters, and then a copy constructor on function exit (return-by-value). If you've got four, there's something you're not showing us or your compiler is broken.

      It is perfectly acceptable to elide some of these where the effect of doing so is invisible, and indeed it is common practice to do so for efficiency reasons; look up the "named return value optimisation", for example. However, that won't matter unless either your class's semantics are blatantly broken: not matching any new in a constructor with a corresponding delete in the destructor, copy assignment that doesn't use copy-and-swap or some similarly safe idiom, etc. (Actually, it probably won't happen at all if there are memory management things in your constructor/destructor, unless your optimiser is very smart at working out that their effects will be invisible if the call is elided, which I don't think any today are.) The only other issue is performance if new is relatively slow, in which case you shouldn't be complaining that any decent compiler will optimise away some of these calls and their attendant memory management overhead.

      Its the fact that its requesting memory at all. If the OS would need to walk the free page list to satisfy the request (or worse- page memory), thats a huge performance hit.

      So write your new operator for the relevant class to use a memory pool you manage yourself like a grown up, and don't trouble the poor, under-powered operating system if it isn't fast enough. This is in chapter 2 of the newbie guide.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    33. Re:Who cares? by Anonymous Coward · · Score: 0

      Comparing templates with "typeless" code is pretty much like comparing long to to green. You can do both "typed" and "typeless" code in both C and C++.

      Memory on the stack is allocated in exactly the same way in C and C++.

      If the temporary objects you don't know call new to create buffers, it can really kill you - just like a call to a library function you don't know, which calls malloc. Nothing happens behind your back here, compared to C - just the C++ syntax is a little different.

      C++ really is an overly complex language, no one doubts that. Yes, there are much more features compared to C, and, like any features in any language, they may be abused, and they may lead to bad code (operator overloading is probably no. 1 here). However, you may write good clear code both in C++ and C. C++ allows you to be more concise, more high-level. It's up to you whether you give up the transparency of your code for it. And what's especially good about C++ for system programming is that it allows you the same degree of control as C does.

    34. Re:Who cares? by s0lar · · Score: 2, Informative

      > (a) looking for problems
      This is a boolshit argument - you get problems with C too. Big problems with "evil macros", memory leaks, resource dead locks, pointer arithmetic, stack corruption etc. It's a matter of expertise, regardless of the language.

      Sure, the C way seems transparent and obvious, but complex problems require more involved solutions. Solutions that abstract building blocks in order to manage this complexity. Abstraction mecanisms are much better with C++. The same goes for encapsulation - OO way provides several useful mechanisms than "static".

      > (b) a C++ bigot that can't see what he is writing is really just C anyway
      The point Stroustrup makes is that one can use a subset of C++. It's a valid thing. However, OO concepts are native to the language, so no function pointer assignments are required to implement abstraction. No "just return a handle" hacks are required to have encapsulation. Why not use a language that natively supports and checks for polymorphism, abstraction and encapsulation?

      Now, all of this is described much better in a "Conversation with Bjarne Stroustrup" by Bill Venners here:
      Part 1: The C++ Style Sweet Spot http://www.artima.com/intv/goldilocks.html
      Part 2: Modern C++ Style http://www.artima.com/intv/modern.html
      Part 3: Abstraction and Efficiency http://www.artima.com/intv/abstreffi.html

    35. Re:Who cares? by mcc · · Score: 1

      Make it a standard code practice

      A serious problem is hidden within this one line, though. What if you are, as the Linux kernel is, not a discrete organization but a large and multifarious community effort? "Then don't use it" is a lot harder to enforce in such a situation. Naming and comments are one thing. But if someone misuses constructors, static object allocation or exceptions in a kernel patch, that requires close inspection to detect and actual recoding to fix if people do not strictly keep to the code standards. I do not know, but I would suspect that having to police all this stuff might make the life of the central kernel maintainers, who are used to C, a lot more difficult than if they just said "C only". That might leave these neat C++ extensions forever limited to be a fork.

    36. Re:Who cares? by AuMatar · · Score: 1
      Comparing templates with "typeless" code is pretty much like comparing long to to green. You can do both "typed" and "typeless" code in both C and C++.


      Yes, you can- but I was arguing why templates may be bad for OSes and embedded systems. Code size is an issue there.

      If the temporary objects you don't know call new to create buffers, it can really kill you - just like a call to a library function you don't know, which calls malloc. Nothing happens behind your back here, compared to C - just the C++ syntax is a little different.


      Except if foo() calls malloc, you know that you called foo. You told it to call foo. WIth temporary objects, you don't know when/where they're going to be created. Even experienced C++ developers get that wrong. Its a much harder issue to track down.

      I disagree that C++ allows any "higher level" coding than C. Object Oriented programing is quite possible in C. Not to mention that while its useful, its not the silver bullet and isn't always the best solution. C++ has features that may occasionally be useful, but it isn't suited for OS and embedded apps. Especially not for an existing project thats already done in C.
      --
      I still have more fans than freaks. WTF is wrong with you people?
    37. Re:Who cares? by Anonymous Coward · · Score: 0

      w00t, CS class! I cares. As a CS student who learned Java and C++ to start off with, it's difficult migrating to non-Object Oriented languages.

      p.s. I love Java Objects.

    38. Re:Who cares? by dpuu · · Score: 2, Insightful

      C++ sucked 12 years ago, so attempting to support it now, 12 years later is a stupid idea.

      Sorry, that argument doesn't quite work for me.

      As I understand it, this patch would simply add runtime support to give a kernel-module-writer the option of experimenting with C++, if desired. Accepting it would not force anyone to use C++. It possibly that the patch itself could be written in C, not C++, so accepting it (or a similar patch) need not introduce C++ into the kernel.

      Once that support is there, you could leave it for a few years while experimenting. No one is forced to rewrite any code (unless they want to). In the meanwhile the kernel becomes increasing modular and, one day, one of the core subsystem might choose to use C++. For example, the VM subsystem could choose to use C++ without having any visible impact on other subsystems.

      Linux moves forward through evolution, not revolution. Add the support, and see if its useful. If it is, people will eventually use it as the old maintainers drift away.

      --
      Opinions my own, statements of fact may contain errors
    39. Re:Who cares? by Percy_Blakeney · · Score: 1
      To get any substantial benefit for existing code, you'd need to translate the entire kernel into idiomatic C++, which is a huge task.

      It depends on what kind of benefit you're looking for. If it is a performance benefit, you could easily take a limited part of the kernel, use exceptions and objects, and be able to show that it is faster or slower.

      You, however, seem to be more interested in the style and maintainability of the code, which is very difficult to qualify. "Easier to understand" is all in the eye of the beholder, and I doubt that the beholder that oversees Linux thinks C++ is easier to understand and maintain in a low-level kernel setting.

      Speaking of maintainability, there is a huge problem with supporting new C++ code in the kernel. It is truly ugly to have multiple acceptable coding paradigms in a large project and would arguably increase the number of bugs in the kernel. You aren't going to be able to just zap away all the old C-style code; it will take years to get it all out. Thus, by supporting both C and C++ code, you end up with a big mess. Is it manageable? Maybe, but it would require a *huge* benefit (performance-wise and maintainability-wise) to justify such a steep cost.

    40. Re:Who cares? by Foolhardy · · Score: 2, Informative
      Temporary objects. Compilers create temporary objects, especiall arounjd function calls/returns. These call the constructor, which may call malloc. The number of situations temporary objects can be made is actually failry high and very complex. If the language is creating objects you don't explicitly ask for and calling malloc off that, I count that as the language using memory. Its the fault of the language for creating the object.
      Don't use classes that call malloc on copy. This would be the library in which the class belong's fault. Either that or always pass by reference or pointer; no copy required. Use const if you don't want the value changed. This can be a rule for the project.
      Like I said- function pointers. Like this:
      You're right. I wasn't thinking about that. Still, you can't inline across function pointers. That could lead to bigger code if the function body uses less instructions than a function call.
      struct outer{
      int handle;
      }

      struct inner{
      int x,y;
      }

      int some_privlidged_func(outer *o){
      inner *in= (inner*)o->handle; //now just reference inner->x and inner->y
      }
      Ick, this assumes that sizeof(int) == sizeof(void *); that is a bad assumption for portable code. Also, you have a one member structure. A better idea would be an empty structure for outer; cast a pointer to outer to get inner.
      I guess this would work pretty good, although you would have to maintain functions to access any data inside of inner whereas you could get to it directly with public. That was my point, that public/private is more convenient than handles. It lets you concentrate more on important things rather than wasting time writing glue functions, as you must to access any properties of a handle.
      It gives them additional ways to break the rules. The more rules, the more people will want to break them, or just waste your time disagreeing with them. Its a social problem, not a technical one. And with larger teams, its a larger problem (with small teams the team probably made the rules themselves and hashed out differnces then). On a small 3-5 person project restricting features works. On large ones it just becomes a hassle. On very large ones with more than 1 gatekeeper to the code, it breaks down entirely (all you need is 1 lazy/disagreeing member with check in privlidges).
      Kernel code already has a million ways to do bad things. Having a different language won't make it much worse. Done properly, C++ can help you write better code that is MORE resilient to idiocy, not less, using namespaces, new types by overloading, smart/safe pointers, templates, member protection...
    41. Re:Who cares? by WindBourne · · Score: 1
      ok, a couple of things.
      • I played with the C++ that was in the kernel back then. It was not so bad. It did have its' issues, but, all things settle out.
      • C++ has as open of mem allocation as you want. You have the choice to handle it or not.
      • C++ exception handling is only broken in that it is not enforced all the way through, the way that Java is. I am not wild about how to handle the stack, but it does enforce better code.
      • OO design in C plain sux. A big part of a good OO is to enforce initialization and clean-up.
      • BEOS already showed that C++ in a kernel can do a good job.

      Now, with that, do I wish to see C++ back in the Linux kernel? Not a chance. Why? because I have seen VMS, and it is not pretty. It has Assembler, PL/1, Cobol, and a few other lang (for some odd reason, I seem to remember RPG in there,but....). It basically meant that one person could not help in another area. Also, jumping from a procedural design lang, to an OO design is a BIG mistake. Better to keep things on the same track. If somebody wishes to redo the Linux kernel in C++, then they should simply re-code it into C++ while making use of Linux drivers via an adapter.

      --
      I prefer the "u" in honour as it seems to be missing these days.
    42. Re:Who cares? by Anonymous Coward · · Score: 0

      LMAO.

      Man, you C++ bigots just got bitch slapped by Linus.

      You young C++ children need to learn to respect your C elders.

    43. Re:Who cares? by photon317 · · Score: 1


      What the C/C++ world really needs is a "C+" of sorts that bridges the gap. C+ would be plain old C99, with the following C++ features added:

      structs can also be called "classes"
      structs can have member functions, including constructors and destructors.
      struct data and function members can be either private or public.

      The above just saves a whole lot of typing and macros and other crap that people do when they write OO-style C-code, without adding the more complex C++ features that people argue about.

      Beyond the ones above, you could also *possibly* add the following, maybe, I'd really have to think about it more than I am for just a /. comment:

      Simple inheritance
      Operator overloading
      Simplistic templates (this one is a real low probability maybe...).

      Do it all in a way that doesn't break the rules of C99, and is syntactically compatible with C++ where they overlap features, and you'd have a fine language I would love to use.

      --
      11*43+456^2
    44. Re:Who cares? by SEE · · Score: 1

      Well, I don't want to start a flamewar here, but while this may be true for the GNU compiler, it certainly is NOT true for, for example, the Microsoft compiler.

      Okay. However, if it is true for g++, then that's enough to keep C++ out of the kernel right there. Unless you're seriously suggesting that compiling the Linux kernel be made dependent on the Microsoft compiler . . . .

    45. Re:Who cares? by Anonymous Coward · · Score: 0

      "superior" type checking doesn't let me use malloc() without a cast. That's a disadvantage. If you're writing C, use a C compiler.

      C++ is an OK idea, but a horrible implementation. It's huge, ugly and bloated.

    46. Re:Who cares? by Anonymous Coward · · Score: 1, Interesting

      Well, I don't want to start a flamewar here, but while this may be true for the GNU compiler, it certainly is NOT true for, for example, the Microsoft compiler. (I know, how dare I say that...) It has produced code from C++ source for a _very_ long time and even the optimizer works very well.

      Most of the Windows kernel is written in C++, too, right?

      Why [are exceptions broken]?

      Exceptions break out of the current function and clean up automatic variables. That's all they do until they're caught. All the hard work is making sure that data consistancy is maintained throughout all your objects during exceptions. It's just as simple to have one part of your function do cleanup and put goto statements to that part instead of bothering with exceptions. I imagine Linus says they're broken because they don't provide any additional benefit over the goto approach, but can be mistaken for providing data consistancy.

      But why would you if you can do it cleaner in C++ and have the compiler generate the same quality code? What is crap about C++?

      The problem is the extra data checking and other things that C++ adds on. For instance, the copy constructor is not optimized (at least in g++), and for instance if you are returning an instance of a class from the function, the copy constructor is called at least three(!) times to return the value. Once to copy whatever return value is created into the local variable at the end of the "return" statement, once to copy that variable into a temporary stack variable in the calling function, and then again to copy that stack variable to the lvalue of the function call. That's standard C++, and there are a few optimizations that can be used, but in general you end up doing a lot of extra work for no reason. You can't optimize those extra copies out because it's an undecidable problem to check whether or not side effects of directly copying to the original function's lvalue will cause race conditions or undefined behaviour, so all three copies are done. Obviously, for performance, the solution is to pass a reference to your local variable into the function so that only a single copy constructor (or other operator) is called, but that's *exactly* what you'd do in straight C. What's the advantage again?

      You don't have to use all the bells and whistles, shit, you can write plain ANSI-C and still use a C++ compiler for it's superior type checking etc.

      So that you have to write *(( datatype *)((int unsigned)&voidpointer+voidoffset))=(datatype)value ; and other nonsense when doing memory management?

    47. Re:Who cares? by Sigma+7 · · Score: 1
      Well, I don't want to start a flamewar here, but while this may be true for the GNU compiler, it certainly is NOT true for, for example, the Microsoft compiler. (I know, how dare I say that...) It has produced code from C++ source for a _very_ long time and even the optimizer works very well.
      I've run into some constructs that were valid C++, but were either rejected by the MSVC compiler, or caused a crash during the build process. I don't have a specific example, but they were found in the FreeCNC Project.

      Of course, this is with the MSVC 6.0 compiler - ancient technology. I can't say fore sure, but I suspect that Microsoft probably fixed these bugs.

      You don't have to use all the bells and whistles, shit, you can write plain ANSI-C and still use a C++ compiler for it's superior type checking etc.
      Not quite... Consider this statement:
      char *ptr = malloc (3200);
      This is perfectly valid in C, but a C++ compiler will complain. (You may have to use a different data type for the complaint to arise, but you will encounter a problem.) The only way to remove the error or warning is to use an explicit C-style cast or a reinterpret cast, both of which make the source code look more cluttered than it should be.

      But other than this small problem, C to C++ conversions should be smooth (unless you are playing with a memory buffer of inconsistant datatypes packed together).

    48. Re:Who cares? by HidingMyName · · Score: 1
      Constructors and destructors are a source of implicit changes to flow of control that that can cause errors in large rapidly evolving projects. Consider a piece of code that looks like:
      SomeType x, y;

      y = 3;
      x = y + 5;
      Suppose this code is written in C++, can you tell me what it does? In fact that is only possible if you have read all the definitions of SomeType and any classes that it may inherit from. Operator overloading forces the reader to look at all definitions inherited when determining what the "=" and "+" operators do. Add exception handlng to the mix and it will be very hard to make the kinds of guarantees about layout, timing, flow control and order of evaluation that need to be enforced in a working kernel. While C is far from perfect, C++ doesn't appear to be a viable solution for kernel devleopment.
    49. Re:Who cares? by slashdot.org · · Score: 1

      Okay. However, if it is true for g++, then that's enough to keep C++ out of the kernel right there.

      Sure. I'm actually not convinced that g++ has issues, but I don't know. If there are, then Linus should perhaps point them out so that they can be fixed. I _do_ know that there were serious issues in 1992 with g++, so I understand where he's coming from. But you can hardly base any argument on the state of software 12 years ago.

      Unless you're seriously suggesting that compiling the Linux kernel be made dependent on the Microsoft compiler . . . .

      No, I'm suggesting that Linus should not make overly broad statements that he doesn't back up. But, there are alternatives to g++, like Watcom.

    50. Re:Who cares? by slashdot.org · · Score: 1

      "superior" type checking doesn't let me use malloc() without a cast. That's a disadvantage.

      To you its a disadvantage, to me it's not. If the compiler tells me about one single error that I don't have to debug because of that, it's worth it to me.

      Then again, I'm probably a shitty coder. I don't trust myself doing things right 100% of the time, so I like to get any automated help that I can.

      C++ is an OK idea, but a horrible implementation. It's huge, ugly and bloated.

      huge - this is simply a myth. Yes, if you pull in the standard library stuff with operator overloading and the works, sure. I write code for embedded systems, so I've done many tests, and I keep a close eye on my binary size. I can create a binary that has the exact same size as the C counter part.
      ugly - well, that's subjective. If you feel that way, fine.
      bloated - how is that? My original comment was a complaint about not justifying overly broad statements, so I don't see how this is going to make me say 'ah, yes, my bad, you are right C is better!'.

      It'd be nice to have an argument about it with real points.

    51. Re:Who cares? by Pseudonym · · Score: 2, Interesting

      Precisely, which is my main point: Writing the Linux kernel in C++ is a waste of time because right now, it's already written. Given that nobody wants to waste their time on this, we will never know if Linux is better written in C or C++.

      I can only speak from the point of view of maintainability and readability, but you make a good point that if Linus et al can't read C++, then even this isn't necessarily an advantage.

      It is truly ugly to have multiple acceptable coding paradigms in a large project [...]

      Actually, most large software projects are multi-paradigm. This is because most large software projects have a "soft layer" DSL/scripting component (e.g. Emacs lisp). An OS kernel is a bit special in this regard, in that most of it is low-level stuff held together with internal APIs. The "soft layer" of Linux is user space.

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
    52. Re:Who cares? by gunpowder · · Score: 1

      Well, IIRC the old NeXTSTEP (3.3 and below) were using Objective-C in the kernel, at least in some drivers. I don't think this is still the case with MacOS X.

      I fully agree that Objective-C is not a viable option for archiving the highest possible performance (and that is what many users what in a kernel, besides stability).
      However NeXTSTEP/OPENSTEP/MacOS X is based on Mach (which already does some sort of message passing), and the Objective-C message passing was/is highly optimized and integrated into the Mach subsystem, so that the performance impact is rather low ...

    53. Re:Who cares? by swillden · · Score: 1
      struct some_type x, y;

      init_some_type(&x);
      init_some_type(&y);

      some_type_op1(y, 3);
      some_type_op1(x, some_type_op2(y, 5);

      Can you tell me what that code does?

      It's only possible if you've read all of the definitions of some_type, init_some_type, some_type_op1 and some_type_op2. Oh, and as far as exceptions... what if some of those C functions call longjmp()?

      Looks like C isn't a viable solution for kernel development either.

      I've written embedded C++ code. I've written embedded operating system code in C++. It works fine. You have to know what you're doing, and you have to decide what features of the language you intend to use. For that matter, you have to do that when you're writing C also -- have you taken a look at the coding guidelines for the Linux kernel? There's *lots* of stuff that you can write in C that Linus will reject.

      Because Linus dislikes C++, this will never make it into the Linux kernel, but that doesn't mean C++ in the kernel is a bad idea. All of the major SVR4.2+ UNIX kernels have some C++ in them. That includes AIX, HP/UX, Solaris...

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    54. Re:Who cares? by Foolhardy · · Score: 1
      Suppose this code is written in C++, can you tell me what it does?
      Suppose this code is written C, can you tell me what it does?
      f();
      In fact that is only possible if you have read all the definitions of f() and any functions it calls. It needs documentation.

      Anyways:
      Objects x and y of type SomeType are created with the default constructor.
      You call the assignment operator on y with an argument of 3: you should have initialized y with 3 when you declared it.
      The addition operator is called on y with an argument of 5. The return value of this function will likely become a temporary, assuming a normal use of this operator.
      The assignment opeator is called on x with a parameter from the return value of the above function. You should have initialized x to this value instead of using assignment (assuming a sane definiton of the assignment operator).
      In fact that is only possible if you have read all the definitions of SomeType and any classes that it may inherit from.
      This is only true if you have no standards on the code in your classes. Done correctly, it does not matter how the functions work as long as they are correct and their dependencies are known (when needed).
      Operator overloading forces the reader to look at all definitions inherited when determining what the "=" and "+" operators do.
      While it is possible to make the "=" and "+" operators do stupid things like output "HI" to the console, that is delibrate obfucation of code; abuse of the language. Operator overloading should only be used when it provides simple and intuitive convenience to code. If SomeType.operator =() doesn't do assignment then it shouldn't be overloaded. If SomeType doesn't make sense to use + with then that souldn't be overloaded either. You could easily make it a code policy that operators cannot do anything more than trivial processing: that they cannot allocate/free memory, access anything outside the class or parameters, or raise exceptions. Any deviation from this policy would represent invalid code. That way, you wouldn't need to know how the the operators work, just that they do what is obvious without complications. This is the basis of abstraction. You face the same need for standards for writing ANY function.
      Operators, like many things can be bad if used incorrectly. So can pointers.

      A good use of operator overloading is the creation of new types. Take a 128 bit integer: most compilers do not have a primitive type for it. In C, you would have to make specialized handling every time you wanted to use the number; a typedef would be out of the question. You would have to maintain a seperate code base for this; you would have to make sure every change is replicated across both sets of code. With operator overloading in C++, you simply overload the operators to do the same thing they would do with a primitive type. The new type can be used with exactly the same code as an int64 and the meaning will be just as obvious.
      Add exception handlng to the mix and it will be very hard to make the kinds of guarantees about layout, timing, flow control and order of evaluation that need to be enforced in a working kernel.
      If you read my earlier post, you would know that I never advocated the use of exceptions; in fact, I try to avoid them.

      C++ is every bit as detirministic as C is. It is one of the language's biggest strengths. Order of evaulation is exactly the same, BTW.
    55. Re:Who cares? by Anonymous Coward · · Score: 0

      OH C++ is too hard to use with & and const. Nobuddy nows how to do it wright.

      BOO *fucking* HOO.

      I think C and * is too hard.

      We should all switch over to Visual Basic .NET 2003!!!!1111!!!oneone!!exclimation point111

    56. Re:Who cares? by dpuu · · Score: 1

      >> Member functions are nice for associating a function with an object.
      > We have that. Function pointers. Kernel uses them all over.

      With a function pointer, you pay for an extra pointer indirection: member functions on a class do not suffer that overhead unless they are virtual -- in which case the cost will be essentially the same as for C (if you need to pay attention to the structure of your vtable -- say, to avoid cache-thrash -- then you may decide to use tables of function pointers, even in C++)

      --
      Opinions my own, statements of fact may contain errors
    57. Re:Who cares? by Foolhardy · · Score: 1

      There IS an offical distrobution. There are specific people that decide what code goes into this package. They do have standards. I can see it as a practical problem for the Linux kernel if all the current devs are used to C only, but that really isn't a good reason to not use C++ in general for kernels. The community has changed in the past; this wouldn't happen overnight.

      C is plenty possible to abuse, espescially in kernel code. I've heard about all kinds of kernel patches that were not put in the main distro because they were messy/unstable without serious clean-up.

    58. Re:Who cares? by Jeremi · · Score: 1
      BEOS already showed that C++ in a kernel can do a good job.


      ObNitpick: The BeOS kernel was written in C. It was the API user-land libraries and APIs that were written in C++.

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    59. Re:Who cares? by Anonymous Coward · · Score: 0

      I disagree that C++ allows any "higher level" coding than C.
      Templates

    60. Re:Who cares? by scotch · · Score: 1
      I think you misunderstand many things about C++, but heres an important one:

      I'm saying to use member functions for the orginazation they provide. You could get somthing similar with a good naming convention. This OTOH is supported by the language.

      Like I said- function pointers. Like this:

      struct foo{
      int (*bar)(int);
      }

      foo has a member bar, which is a pointer to a function that takes an integer and returns an integer. You assign it like: foo->bar=myfunc; This is exactly what a member function does- the only difference is that the this pointer won't exist, so the first parameter to any member function would have to be a pointer to itself. You can even call it this :)

      When you say "this is exactly what a member function does" - you're wrong.

      Your stuct wastes one word per object per "member" function. For non-virtual functions, C++ uses 0 words per object for member functions. for virtual member functions, C++ uses one word per object regardless of the number of virtual member functions. So in the first case, with your approach, you're paying a huge space overhead and 1 indirection. C++ is paying no space overhead and no indirection - everything is known at compile time. For the case where virtual functions are used, you still pay less space overhead in C++, but you get an extra indirection. C++ is smart enough to know at compile time whether the virtual dispatch is needed or not. This is an important difference that you don't seem to understand.

      Finally, storing function pointers in objects (stucts or classes) is perfectly valid in C++, if you are disatisfied with the static or dynamic binding mechanisms provided. ;)

      PS - many of the details above are implementation defined, but the above is the usual approach.

      --
      XML causes global warming.
    61. Re:Who cares? by Anonymous Coward · · Score: 0

      Yes- because everyone always uses & and const correctly, right?
      If they don't, they have no fucking business writing kernel code for production use.

      Most C++ developers don't know what the difference between a reference and a normal variable is, much less declare everything they need to const.
      Right, because your sweeping generalization is so well-researched and well-cited. No wait.. it's just bullshit!

      Not that I blame them ont he second- keeping track of what needs to be or can be const is annoying as hell, and you're bound to fuck it up so many times you give up.
      If you can't keep track of what needs to be const, you shouldn't be writing C code either because it's just as relevant in C. At least, as far as being a good developer and allowing your code to communicate with other developers who read it goes.

      You blame C++ for the fact that bad programmers write bad C++ code. Well, guess what, bad programmers write bad C code, bad programmers write bad Java code, bad programmers write bad LISP code, and bad programmers write bad assembly code. Bad programmers write bad code. End of story. That's not the language's fault!

    62. Re:Who cares? by scotch · · Score: 1

      I think the only thing you're doing is convincing people you don't know much about C++. Pass by reference isn't hard - not even remotely one of the advanced topics in the language. Const is also a keyword in C, btw, it just has more uses in C++ because of the class syntax.

      --
      XML causes global warming.
    63. Re:Who cares? by Anonymous Coward · · Score: 0
      Can you tell me what that code does?

      Fails to compile. You forgot a right parenthesis.

    64. Re:Who cares? by thebatlab · · Score: 1

      From linked article:

      # Is it a good idea to write a new driver in C++? The short answer is no, because there isn't any support for C++ drivers in the kernel.
      # Why not add a C++ interface layer to the kernel to support C++ drivers? The short answer is why bother, since there aren't any C++ drivers for Linux.

      Hmmm...maybe he should quit giving "short answers" that lead you in a circle and instead actually come clean on why he doesn't want this. Any post related to C++ in the kernel, he ends up coming across like a pretentious ass who thinks nobody that wants it done will understand his reasons for not doing it. "Trust me". Famous last words.

    65. Re:Who cares? by Anonymous Coward · · Score: 0

      You DON'T HAVE TO use a garbage collector. You CAN write memory management the old way.

      OO with C is a stupid and awful hack.

      What is it with you people? Are you idiots or something? Have you no clue about C++?

    66. Re:Who cares? by Anonymous Coward · · Score: 0

      The VMS kernel was written entirely in BLISS and some assembler. As for the VMS applications, they were written in whatever language, which is the same as most Linux-based systems.

      Bruece Miller - brm@yoyodyne.com

    67. Re:Who cares? by Anonymous Coward · · Score: 0

      It would not force anyone to *write* C++, but then moment someone starts doing it, it would force people to *debug* C++.

      And since all the main developers are C programmers, how much experience do you think they have debugging C++ code?

      If the official kernel ever starts supporting code written in C++, expect another tainted flag to be added.

    68. Re:Who cares? by Baki · · Score: 1

      All true, but it can be very useful for existing code. I would not put it in the core of the kernel, but especially in the case of device drivers it is imaginable that existing drivers can be adapted for use into linux much more easily (i.e. much less porting to do) if they can be kept in c++ if that is the language the existing driver was written in.

      It would not destabilize the rest of the system, but those who actually use the device driver should know that it might bare certain risks for the overall system. But that may be better than nothing in those cases where a full port from c++ into c would be too much work (e.g. for niche devices where not many developers may be interested to invest a lot of time).

    69. Re:Who cares? by ebbe11 · · Score: 2, Insightful
      Not quite... Consider this statement:
      char *ptr = malloc (3200);

      Except that in C++, you'd write:

      char *ptr = new char[3200];

      and not have any problems at all.

      --

      My opinion? See above.
    70. Re:Who cares? by tchernobog · · Score: 2, Insightful

      If you don't think thats a problem- try putting a cout statement in a constructor, and write a function that takes an object as a parameter and returns that object.

      Although I agree that c++ isn't a good choice for a kernel, here i've to say that you can in fact produce good code simply remembering to pass args to a function as constant references. You've a good control over when and why temporary objects are created, if you fully understand what your code does. More, modern compilers like g++ use optimizations to avoid creating non-wanted temp objects (like in "C* obj = new C(C(otherobj));") and thus eliding redundant constructors (that was a silly example, but there's plenty of situations).

      I believe that for a good c++ programmer memory management is simplier and cleaner than c's one, instead of loose and chaotic. This doesn't mean that malloc() sucks; it just means that new/delete aren't evil and help you if you know how to use them.

      Assembly gets a bad rap, really its a nice simple language.

      Simple doesn't mean portable.

      The gain of c++ over c is really substantial, BUT I don't think that c++ is a good choice for kernel development, mainly because it's too "tempting" to add millions of useless features. c is neat, easy and has a really small grammar: it's something you can learn in a week. c lets you to act to a more lower level, is faster to compile, and extremely portable (that's the main reason why Linus won't like c++). I believe that c lets programmers to concentrate more on the real algorithmic problems of the code (such as sorting, scheduling, threading...) than on inheritance/class (syntactic) related ones.

      --
      42.
    71. Re:Who cares? by ebbe11 · · Score: 1
      The second- C++ has hidden allocations all over.

      No, it hasn't. Some of the C++ standard libraries (especially STL) have hidden allocations all over. So don't use those libraries. Problem solved.

      The real question is- what does C++ give you that C doesn't?

      In my experience:

      • Much cleaner code design leading to code that is much easier to maintain. Remember, the objective is not to make code that works. It's to make code that keeps working.
      • When inheritance is done right it means less code to write, meaning faster time-to-market.
      And yes, I write embedded real-time software too - in C++.
      --

      My opinion? See above.
    72. Re:Who cares? by Mock · · Score: 1
      exceptions are a Bad Idea. Error codes are much
      cleaner and more logical


      As far as cleaner goes, it depends on your perception. If you mean cleaner in the sense that less code is generated, I'd agree. However, from the programmer's perspective, it's much messier to constantly put checks everywhere to propagate the fact that an error condition has occurred to the upper levels.
      As far as logical goes, that's an unqualified opinion. Why is a number stored globally and checked from time to time more logical than code that checks for an OutOfMemoryException?

      In C, its easy to find memory allocations. Grep for malloc (or kmalloc in the kernel)

      In C++, grep for new (or new in the kernel).

      In C++, you have temporary objects being instantiated all over the place

      Same thing in C. Ever heard of a struct?

      If you don't think thats a problem- try putting a cout statement in a constructor

      Would you use cout in a kernel? I wouldn't.

      write a function that takes an object as a parameter and returns that object
      AnObject& passObject(AnObject& obj)
      {
      // do something here
      return obj;
      }

      or

      AnObject* passObject(AnObject* obj)
      {
      // do something here
      return obj;
      }
      I count 0 temporary objects being created.
      Working with objects in C++ is pretty much the same as working with structs in C, except you can do cooler stuff with objects.

      A large amount of object creation doesn't make sense in an embedded/kernel environment.

      Really? So all those structures being created by the Linux kernel are a bad thing? I never knew a file descriptor could be so evil...

      Objects- C has them
      Yes, but the population and control logic associated with them has to be written externally... Another word for this is a hack.

      Inheretance? Very rarely does it really benefit you, its usually used because "we're OO, we're supposed to use it"
      This is the refrain of the OO novice.
      Repeat after me: OO != Inheritance.

      Inheritance is but one of the many design patterns available to the OO developer.
      Just because Inheritance happens to be the most misused design pattern doesn't mean it's always wrong to use it. People use screwdrivers as prybars all the time, with predictable results.

      Templates? Ok, those can be useful for things like linked lists, although the STL goes way over the top with it.
      Which is of course why you wouldn't use STL in a situation where memory is tight... Much like you wouldn't dump a full-fledged C runtime library into an embedded system.

      The gains of C++ are minimal, the pain of it is large.
      The gains of C++ are substantial. The people who can use it properly appear to be few.
    73. Re:Who cares? by Anonymous Coward · · Score: 0

      I enjoyed reading your arguments on this subject. FWIW, I agree 100%.

      AuMatar's biggest point, however, is the social problem. I got a new job recently where there isn't even time for people to do active code reviews. There's a mix of C programmers and C++ programmers, and the C guys will almost always break interfaces and change them around. The only way around it is to have them restricted to their own modules. Even then, you'd be surprised how difficult it is to get the old guys who wrote nothing but C and ASM to even try and absorb the ideas behind design patterns and good OO design.

      I still agree with you, though. Just, when you hire someone, make sure they use C++ the right way. Old-school C programmers are dangerous to even the best C++ code.

    74. Re:Who cares? by Anonymous Coward · · Score: 0

      Not a hard issue to track down if you overload new and delete to report the locations of where the allocations happened. Oh yeah -- the overloads can happen in 1, centralized spot.

    75. Re:Who cares? by bujoojoo · · Score: 1

      *(d) Profit!

      Oh, wait. Wrong thread. Sorry.

      --
      This space for rent
    76. Re:Who cares? by TaleSpinner · · Score: 1
      >The first argument is easy- exceptions are a Bad
      >Idea. Error codes are much cleaner and more
      >logical.

      Error codes put exception handling code in line
      with code trying to do the main job. They are
      also error-prone because nothing requires you to
      check them. That made them "cleaner and more
      logical" when exception handling was expensive
      in time and memory. The whole point of this
      announcement is that exceptions are no longer
      expensive in time or memory. Exceptions are now
      "cleaner and more logical" - also more reliable,
      more modular, and separate from the code doing
      the actual work, hence more readable.

      >C++ has hidden allocations

      If you use them. The kernel already requires one
      to write code that respects convention. If Linus
      decides the convention should require no hidden
      allocations then such is life, C++ or not. But
      with clean, fast exception handling, hidden
      allocations may not be all that bad.

      Now, C++ is the kind of language where I wouldn't
      trust anyone but myself to write things with it,
      if you take my meaning. But to be honest, if I
      were to trust anyone else with it, that
      anyone would be Linus. He has taste. =)

    77. Re:Who cares? by Sigma+7 · · Score: 1
      Except that in C++, you'd write:

      char *ptr = new char[3200];

      and not have any problems at all.
      Actually, there is one problem that remains. Under C/C++, you are allowed to do questionable things like defining macros so that malloc is redirected to a special debugging function. For example:
      #define malloc(s) _log_malloc(s, __FILE__, __LINE__)
      (This is a basic transparent memory leak detector - it redirects calls to malloc to a special function in another module being liked. In turn, the function calls malloc and keeping the file and line information just before the pointer returned to the user. There may be complaints for using a macro, but that's a style issue. )

      While I haven't been pushing all my effort into this task, it is more difficult to do the same under the new operator for some reason. I could live with a non-transparent equivalent, but that generally causes a minor change in programming style that might not be for the best.

      There is one thing, though - I've just found out how to overload the new operator. While this does help, the information that I found so far indicates that there must be a small change in how I code. (e.g. typing "NEW" instead of "new").
  18. fantastic ... by Anonymous Coward · · Score: 4, Funny

    what an incredibly awesome idea!!!

    i can't wait to try and debug virtual functions, copy constructors, and polymorphism over JTAG or BDM!!!!

    man thats gonna be fun ... my hats definitely off to this academic you have definitely spent your time wisely!!!!

    i always found C causes to much clutter in the linux kernel ... a real language will do us all good ...

    keep an eye for this in 3.0 ...

    Jim

    1. Re:fantastic ... by Anonymous Coward · · Score: 0

      Maybe YOU cant handle it but im sure there are others standing behind you to replace you.

    2. Re:fantastic ... by myg · · Score: 1

      You're right. How do those crazy Apple developers debug their C++ device drivers[*] with only those few JTAG wires? I mean, you would never have a tool that would do that for you, like a C++-aware debugger. I'm sure everybody clocks out JTAG transactions by hand... One morse key for the clock, one for data,... [*] The device driver framework for Darwin is in C++, as is the eCos real-time kernel. I guess I just imagined those.

    3. Re:fantastic ... by Anonymous Coward · · Score: 0

      i can't wait to try and debug virtual functions, copy constructors, and polymorphism over JTAG or BDM!!!!

      Maybe if you started using abstractions in your code, you wouldn't have to use debuggers at all.

      Also, the Linux kernel already has virtual functions, copy constructors, and polymorphism. But they aren't defined in the language, so no tool really knows about them, and unlike their C++ equivalents, very little is guaranteed about them.

      keep an eye for this in 3.0 ...

      Given that kernel developers seem to be spending a lot of time on trivial memory management stuff, buffer overflows, and other mindless chores, it seems doubtful that 3.0 will be much different from 2.6; Linux kernel development has slowed to a glacial pace.

  19. .... so can we compile the kernel by TheRain · · Score: 2, Interesting

    using the kernel now? :)

    Joking aside, this is cool. Runtime compiling makes conceptual sense in an open source operating system running mainly open source software... though it will surely add to load times. It adds to the openess of open source by keeping the source editable straight up untill run-time and, so, encourages keeping source code and editing source code... being that it is immedietly executable, given it was coded correctly of course ;)

    --
    Please help! I'm stuck inside my virtual reality headset!
    1. Re:.... so can we compile the kernel by Anonymous Coward · · Score: 1, Informative

      RTFA. This is not about a compiler in the kernel, it's about using C++ instead of C.

    2. Re:.... so can we compile the kernel by PugMajere · · Score: 1

      That brings a whole new meaning to the term, "self-hosting"

  20. Exercise in Obfuscation by drewzhrodague · · Score: 0, Troll

    Sounds like an exercise in obfuscation. How will SCO handle this?

    --
    Zhrodague.net - I do projects and stuff too.
    1. Re:Exercise in Obfuscation by Anonymous Coward · · Score: 0

      Probably by saying that they did it first and these guys owe them money.

  21. C++ by bsd4me · · Score: 4, Interesting

    I'm not sure if many people remember, but there was a short time when the kernel source was compiled with g++, even though the source was plain C.

    IIRC (memeory very hazy, though), it lasted about a month in 1992 or 1993, and it had something to do with type-safe linking(?).

    --

    (S(SKK)(SKK))(S(SKK)(SKK))

    1. Re:C++ by Lally+Singh · · Score: 2, Funny

      C++ wasn't standardized until 1998. Should I talk trash about C99 by referring to the original K&R version?

      --
      Care about electronic freedom? Consider donating to the EFF!
  22. Here's what's coming up! by Le+Marteau · · Score: 3, Funny

    Support, within the kernel, for IE^H^HMozilla! It'll be perfectly safe! Trust us!

    --
    Mod down people who tell people how to mod in their sigs
    1. Re:Here's what's coming up! by Anonymous Coward · · Score: 0

      They're already working on his for Darwin.

    2. Re:Here's what's coming up! by Anonymous Coward · · Score: 0

      They already got khttpd (kernel space http server).

    3. Re:Here's what's coming up! by maxwell+demon · · Score: 1

      Well, of course X must go to the kernel first. And wouldn't it be nice to have an XMMS kernel module?

      --
      The Tao of math: The numbers you can count are not the real numbers.
    4. Re:Here's what's coming up! by pne · · Score: 1

      Well, given that we already know that "IE is part of the operating system", it just makes sense...

      (/me is reminded of the HTTP server in the kernel, which actually was implemented.)

      --
      Esli epei etot cumprenan, shris soa Sfaha.
  23. Exception-handling changes relevant for g++? by Monkius · · Score: 3, Interesting

    Kernel aside, I wonder if G++ developers out there have any comments on these guys' exception-handling changes?

    Would they be applicable to the user-space runtime?

    --
    Matt
    1. Re:Exception-handling changes relevant for g++? by DonGar · · Score: 1

      That was my thought. It had never occured to me that dynamic casts would be string based not pointer based. Now I think I might need to go research why.

      --
      plus-good, double-plus-good
    2. Re:Exception-handling changes relevant for g++? by halldorisak · · Score: 1

      Just to clarify things... The user space linker ensures that there is one copy of each RTTI object so in user space dynamic type checking is based on pointer comparison. The problem arise in the Linux kernel. The kernel module loader (located in kernel/module.c) does not handle weak symbols to ensure that there is only one copy, so that to be sure that dynamic type checking works string comparison is needed. It seems that the G++ developers have recognized this in the sense that a special preprocessor macro changes the dynamic type checking to string comparison if KERNEL is defined. We modified the linux kernel module loader to ensure that only one copy of a weak symbol exists within the kernel and made sure that the type checking is performed with pointer comparison

    3. Re:Exception-handling changes relevant for g++? by Monkius · · Score: 1

      As my post stated, I was asking about the exception-handling performance changes mentioned in the write up.

      It states:

      "The cost of throwing an exception one level on a 990 MHz Intel Pentium is around 12-13 micro seconds in the plain GNU g++ implementation, which we reduced to 2.1 micro seconds by modifying the runtime library, including unwinding the stack in one phase, and caching information on exception paths. In contrast the cost of a trivial printk operation -- printk("Error\n") -- is 18 micro seconds."

      --
      Matt
    4. Re:Exception-handling changes relevant for g++? by halldorisak · · Score: 2, Informative

      These changes would definately be applicable to user space as well, and indeed we mention it in our paper. In kernel however they are more important as performance is normally of more concern.

      Ideally you should be able to turn on these optimizations by a switch. If any g++ developer is out there I'd be more than happy to explain what we did and they are free to use it.

      Some of the overhead in the g++ exception implementation arises from the fact that ease of debugging is considered important. However in kernel space that does not apply.

  24. Are you serious? by KinkifyTheNation · · Score: 0, Offtopic

    Just this afternoon I pondered if Linux supported C++ like this. With Slashdot I don't have to go out of my way and do things like being social to get things answered anymore. Thanks, Slashdot, for ensuring my nerdyness!

  25. interesting, but not very useful by cout · · Score: 4, Interesting

    Any kernel project that uses C++ is most likely doomed to be an experimental project and will most likely never be included in the kernel. IMO, there's good reason for that, too. The added complexity just doesn't outweigh the benefits of using C++ over C.

    In fact, there was a good post on kerneltrap not to long ago about C++ inside the linux kernel:

    http://kerneltrap.org/node/view/2067

    Worth a read if you've got a few minutes to burn.

    1. Re:interesting, but not very useful by Lally+Singh · · Score: 2, Informative

      essentially a quote of linus's comments from the 1992 test. boo hoo, he tested a pre-standard language and a pre-standard compiler (which was honestly crap on C++ until very very recently).

      --
      Care about electronic freedom? Consider donating to the EFF!
    2. Re:interesting, but not very useful by Anonymous Coward · · Score: 0

      That is simply not true. Take a look at Darwin (MacOS X) kernel, especially IOKit. Here is an excerpt from IOKit help:

      Language Choice

      Apple considered several programming languages for the I/O Kit and chose a restricted subset of C++. This subset is based on the Embedded C++ specification (http://www.caravan.net/ec2plus/).

      C++ was chosen for several reasons. The C++ compiler is mature and the language provides support for system programming. In addition, there is already a large community of Macintosh (and BSD) developers with C++ experience.

      The restricted subset disallows certain features of C++, including

      exceptions
      multiple inheritance
      templates
      runtime type information (RTTI)--the I/O Kit uses its own implementation of an runtime typing system

      These features were dropped because they were deemed unsuitable for use within a multithreaded kernel. If you feel you need these features, you should reconsider your design. You should be able to write any driver you require using I/O Kit with these restrictions in place.

    3. Re:interesting, but not very useful by HuffMeister · · Score: 1

      You probably meant the added copmlexity just outweighs the benefits of using C++ over C, right?

  26. great! by pyrrho · · Score: 2, Funny

    but don't use runtime type checking in the kernel please.

    or exceptions.

    --

    -pyrrho

    1. Re:great! by Lally+Singh · · Score: 1

      You do realize that RTTI is a pointer comparison? And that the costs of exceptions are easily paid for in the reduced number of error checking code that tries to handle manually (and at every function) what exceptions do automatically. Not to mention that it gives the compiler more knowledge of what's going on, and thus more opportunity to optimize.

      --
      Care about electronic freedom? Consider donating to the EFF!
    2. Re:great! by pyrrho · · Score: 2, Interesting

      I'm a bit out of date on RTTI implmentations but I did see that mentioned, which sounds great. A pointer to what though?

      Anyway, RTTI can be a great thing (and beats building your own dynamic typing system when you need one) but I'm with Stroustrup that the need for one shows improper design in the most general case.

      btw, I love C++. The point is that C++ has many available paradigms and idioms available, this gets it a lot of teasing... but it's a strength... a project is to choose the idiom it prefers and stick with it.

      --

      -pyrrho

    3. Re:great! by BCoates · · Score: 1

      A pointer to what though?

      I think you just compare the virtual-table pointer that's already in the object. same virtual-table, same dynamic type.

    4. Re:great! by 12357bd · · Score: 1

      or dont try to make it real time too.

      --
      What's in a sig?
    5. Re:great! by be-fan · · Score: 1

      This is theoretically true. This is generally not implemented in C++ compilers, though, because C++'s loose semantics for pointers makes such optimizations very difficult to do.

      --
      A deep unwavering belief is a sure sign you're missing something...
    6. Re:great! by halldorisak · · Score: 1

      this of course depends on the C++ implementation but G++ compares the pointers to a Type Information object (the one that is returned with the typeid operator). The second entry in each virtual table produced by G++ happens to be a pointer to this type information object.

    7. Re:great! by Lally+Singh · · Score: 1

      An instance of type_info.

      Yeah, a smell of bad design, but that'll happen as you build lots of code, *then* have requirements change :-)

      I agree. The biggest problem C++ has is that there are lots of jackasses who feel that they need their language to tell them how to program, and they see C++ as a land of anarchy & danger instead of power & flexibility.

      --
      Care about electronic freedom? Consider donating to the EFF!
  27. I take exception... by IceAgeComing · · Score: 4, Informative


    I've only written one linux driver, so I'm no expert, but I can think of situations where exceptions can be helpful for device drivers.

    Take, for example, a game controller or other hardware device that can become unplugged at any moment. It's useful to have an elegant way of handling this uncommon occurrence.

    Exceptions are a useful way to separate uncommon sanity checks from the rest of your code, so you're not forced to use ugly nested conditionals.

    1. Re:I take exception... by Anonymous Coward · · Score: 1, Informative

      You can use setjmp(), longjmp() with the same effect in C without the extra baggage that comes with C++ exceptions.

    2. Re:I take exception... by thogard · · Score: 1

      The original poster is correct. Unplugging a game controller is a normal event.

      Having the USB interface get hit by an alpha particle and telling the driver that it now needs to read 0x01000002 analog axis is an exception.

    3. Re:I take exception... by Anonymous Coward · · Score: 1, Funny

      > You can use setjmp(), longjmp() with the same effect in C without the extra baggage that comes with C++ exceptions.

      You can use the S and K combinators and an "apply" operator, without having to resort to all that extra baggage that comes with "statements" and "numbers" and other needless crap like that.

    4. Re:I take exception... by torokun · · Score: 1

      Sure, but is it worth making everyone go read guru of the week all the time, and know "Exceptional C++" and its sequels down pat?

      I can tell you as a long-time C++ programmer (maybe you are too), probably 90% of the people out there actually writing C++ don't know about the tremendous pitfalls you can fall into with exceptions.

      There are so many things to talk about here, but just as an example, in order to be exception safe, you have to make copies of things all the time in C++. You have to copy, change state, check if you succeeded, if not, throw, and if so, swap the changed state with the original and move on. If you don't do it that way, you could end up throwing with a changed state or have someone below you throw in the middle of a non-atomic operation... aggh.

      IMHO, it's awesome if you really know your stuff, but it's definitely dangerous otherwise.

    5. Re:I take exception... by mc_barron · · Score: 1

      Spaghetti code anyone?
      And this was moded "informative"?!?

    6. Re:I take exception... by Anonymous Coward · · Score: 0

      Unplugging a game controller is a normal event. Unplugging a game controler that is in use, on the other hand, is an exceptional event. That is to say, it should never happen, but we know it can and we have to respond gracefully.

  28. SCO will do: by Anonymous Coward · · Score: 0

    Like they handle everything else.

    * A nice handshake
    * Grease up the 10 feet pole
    * Insert it in

  29. Objective-C by Anonymous Coward · · Score: 1, Informative

    Worse than C++.
    Objective-C is too dynamic, and all objects are heap objects.

    1. Re:Objective-C by tyrione · · Score: 1

      Tell that to Apple. I'm sure they'll disagree strongly.

    2. Re:Objective-C by Anonymous Coward · · Score: 0

      Apple doesn't use Obj-C in the kernel as far as I know. We aren't talking about the application domain here.

    3. Re:Objective-C by javaxman · · Score: 1

      What about @"SOMESTRING" ? That's a compile-time allocation, sure to be on the stack, right?

      Maybe it'd be more correct to say *most* objects are heap objects? Certainly, the memory for the objects themselves is always in the heap. With possibly a few exceptions ( like above, are there maybe others? ), as well as pointers and primitives, of course.

      How about

      static NSString *foo;

      at the top of a .m file, that NSString's memory *is* in the heap, right? yea, that's right - it's just the pointer that's in the stack, the memory reserved in a class' -alloc method is on the heap...

      Of course, there's the notion that for a _lot_ of stuff near performance-sensitive code, you _wouldn't_ usually be using the object calls, and for largish, persistient, frequently-accessed data structures, you'd not pick an object over a primitive if performance was an issue, but then, that's just good common-sense programming practice, right ? ;-)

      The whole point of what these guys are doing with C++ in the kernel is to make using C++ in general a little _less_ slow, as well as bringing in some of the benefits of more modular, reusable code... where it make sense. It's an interesting experiment, at the very least.

  30. So it has come to this. by Anonymous Coward · · Score: 0

    Linus is rolling in his grave.

    1. Re:So it has come to this. by EnormousTooth · · Score: 1

      Oh no! Linus died!
      If I could remember how those Stephen King trolls went, I'd write one.

      --
      I don't use Emacs; it uses me.
  31. A good hacking exercise, but... by Anonymous Coward · · Score: 1

    Every day newer appliances are thrown in the market without Linux drivers; a C++ kernel won't help much in avoiding this. *Please* if you have enough resources/knowledge go test some hardware and help developing drivers for unsupported stuff.
    In other words, put the efforts where they're most needed.

    1. Re:A good hacking exercise, but... by fitten · · Score: 2, Insightful

      In other words, put the efforts where they're most needed.

      I thought F/OSS (and Linux) was all about innovation and exploration... Sure, there are lots of things that F/OSS projects need (not the least of which is some QA effort), but it also needs folks like these people who are out doing cool stuff, even if it isn't necessary practical (or even considered practical by the 'masses' or the 'powers that be').

    2. Re:A good hacking exercise, but... by Grishnakh · · Score: 1

      Yes, but you need some pragmatism too. If F/OSS doesn't get enough work to make it popular enough to survive, then there won't be anything to try your innovation and exploration on. It's not exactly possible to try any innovative ideas out on the Windows kernel, unless you happen to be a MS employee.

      However, with the number of people that seem to have an interest in Linux kernel development, there probably isn't a huge problem here. The problem with device drivers is that you either need documentation (which isn't readily available), or you have to spend massive amounts of time reverse engineering, which is a PITA, and probably not as fun for these people as doing new development, trying out their CS theories, etc.

    3. Re:A good hacking exercise, but... by mccoma · · Score: 1
      innovation and exploration
      if your doing something I think is cool.

      put the efforts where they're most needed
      if your doing something I don't think is cool.

      :)

  32. Who cares? by Anonymous Coward · · Score: 3, Funny

    My VB kernel works just fine for me.

  33. The true nature of C++ :) by kompiluj · · Score: 5, Interesting

    C++ was designed to be the language of choice for modern operating systems, meant to replace C. This is main reason why every decision was made with efficiency in mind (no automatic virtual functions, no garbage collection, and, oh yes!, the infamous: pointers and goto). And of course C++ is fast. Maybe it loses by hair's breadth with C but surely wins with Java by great margin. And don't tell me about JIT, do some homework.
    I think trying to incorporate C++ into Linux kernel is a good decision, giving more vitality to Linux and allowing it to differentiate better from the traditional UNIX systems - but that's only my 0.02 Euro.

    --
    You can defy gravity... for a short time
    1. Re:The true nature of C++ :) by Anonymous Coward · · Score: 0

      I hope you are troll, because otherwise you are a moron, but I'll take the bait. The C programming language is a macro assembler. If you are good when you write in C you know exactly the machine code that will be produced by the compiler. No other compiled language is as powerful and precise.

      C++ is for applications and application programmers. You know, programmers that forget to release memory and can't debug. And programs that see so much garbage data that they only belong in user space. Problem is that there are a dozen newer OO languages that are better for application programming, and even more tolerant of application programmers.

    2. Re:The true nature of C++ :) by Salamander · · Score: 1
      C++ was designed to be the language of choice for modern operating systems, meant to replace C.

      Maybe to some people "operating system" means anything that's not a GUI, but according to standard definitions it is not what C++ was designed for. Even Stroustrup generally avoids any such claims.

      --
      Slashdot - News for Herds. Stuff that Splatters.
    3. Re:The true nature of C++ :) by Anonymous Coward · · Score: 2, Interesting
      Decisions like this (C++ in the Linux kernel) are indicitive of the courses currently running in Computer Science departments world wide.

      Whilst at university I kept up with the compsci courses as well as those required for my physics degree and I have to say I was shocked. There was no C taught at all, and only one course on ASM - a basic first year introductory module which was very leaniently marked. All other "programming" classes were conducted in Java or html (funny given html is a markup language). There was an optional "AI" course which taught a little prolog, but less than could be covered by an average hobbist in 3 nights.

      The java aplications developed were - all in all - no better than what I would expect a decent highschool computer scientist to turn out - simple storage/record keeping apps. The first lesson the freshmen compscis had was how to turn a computer on. "This is the 'power button'". Three students had not used a computer before.

      It was a real eye opener, of the ~100 students enrolled I would have considered employing less 6 of them for a computer related role. There were only 2 I would have employed as programmers, both exception compared with the rest of their cohort.

      I should think that less than half of the graduting class knew what a kernel was let a lone why one shouldn't be written in C++ or Java.

      The Physicists on the other hand became adept at technical multiplatform C programming and were required to take an ASM course which covered the computer science material in a 3 hour afternoon session along with debugging of a 6 A4 page ASM print out for a chip we knew virtually nothing about. ~70% knew at least some unix and virtually all were better programmers than their comparable computer scientist friends, example programs written included a ray tracing app, a graphical simulation package for complex elecomagnetic fields, and galaxy formation simulations.

      The trend continues into postgrad life where one of the barely employable compscis is working towards a PhD in network traffic analysis, despite at our last interaction him not knowing anything about data networking, other than you push the cable with the funny shaped plug on the end into the wall and it goes to the hub.

    4. Re:The true nature of C++ :) by Anonymous Coward · · Score: 0

      And of course C++ is fast. Maybe it loses by hair's breadth with C but surely wins with Java by great margin.

      Generally speaking there is no difference in performance between C++ and C. Exceptions can slow things and virtual function pointers will also (but you don't have to use those and function pointers in C are slower too).

      However, it's easier to make cleaner code that is faster in C++. The whole template system allows that. You can do the same thing in C, and have the same performance, but it looks like shit and can be hard to maintain.

  34. "The fact is..." he's out of touch by devphil · · Score: 3, Interesting


    Anyone who claims with a straight face in 2004 that "C++ compilers are untrustworthy" is trolling. Sorry, rabid penguin lovers.

    I love it when language bigots forestall any reasonable discussion by preemptively accusing anyone who disagrees with them of being a language bigot. Slashdot, of course, believe that Linus can do no wrong, so none of it ever applies to him...

    After having conversations with him myself, I can state my honest belief that Linus doesn't understand how to use C++, and will simply assert that "it's just C anyway" no matter how many times he's proven wrong. He's a smart guy, but he's got his blinders on in some respects.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
  35. But why should C++ be used in the Linux kernel? by master_p · · Score: 2, Interesting

    The article says that they managed to support C++ in the kernel. Well, that's sweet as an accomplishment. But what are the benefits? many parts of the kernel are already object-oriented, in the form of manually written vtable structs and object structs that have pointers to those vtables. I just don't see a reason for C++ in the kernel. Maybe someone that knows more on this can enlighten us.

    1. Re:But why should C++ be used in the Linux kernel? by Lally+Singh · · Score: 1

      those vtable structs and pointers can now be validated by the compiler.

      C++ also lets you insert code that's needed yet easy to forget, like deleting resources (ala smart pointers) both at the end of its use or when an exception is called.

      And anyone who's actually read more than a quick "C++: classes and templates" book will know where and how the compiler inserts code for you. It's all very well defined, and also done only upon times which become obvious to an experienced programmer.

      --
      Care about electronic freedom? Consider donating to the EFF!
    2. Re:But why should C++ be used in the Linux kernel? by Anonymous+Brave+Guy · · Score: 1
      But what are the benefits? many parts of the kernel are already object-oriented, in the form of manually written vtable structs and object structs that have pointers to those vtables. I just don't see a reason for C++ in the kernel.

      Looking at that statement in isolation and ignoring the kernel specifics for a moment, if you're doing something complicated by hand in one language, and you have available a similar language that can do the same thing as a language feature, using the latter will typically make your code simpler, less error-prone, and potentially more efficient, since the language feature provides more information for an optimiser to improve the output code.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    3. Re:But why should C++ be used in the Linux kernel? by be-fan · · Score: 1

      Well, there are also other benefits. For example, the generic data structures in the kernel are based on the void* model. This is quite a bit less efficient than the template model, which allows a lot better code optimization. That's why STL's sort() is usually 10x faster than C's qsort().

      --
      A deep unwavering belief is a sure sign you're missing something...
    4. Re:But why should C++ be used in the Linux kernel? by iabervon · · Score: 1

      Not necessarily. The kernel's use of objects is essentially to define interfaces and implement them. While there are generally provided defaults for many of the operations (so you don't have to write your own "return -ENOSYS;"), there isn't really inheritance. C++, so far as I know, doesn't have a way of specifying that your use of OOP follows this pattern.

      That is to say, a language feature in one language may support more generality than the idiom you use in a language without this feature, and the may not have a way of specifying that the extra generality is not used. In this case, you may be using a complicated feature to get a simple effect, and you could just do something simple by hand and give the compiler the additional information that you are not doing (or supporting others doing) the complicated thing, making the optimizer work better.

    5. Re:But why should C++ be used in the Linux kernel? by Anonymous+Brave+Guy · · Score: 1
      The kernel's use of objects is essentially to define interfaces and implement them. While there are generally provided defaults for many of the operations (so you don't have to write your own "return -ENOSYS;"), there isn't really inheritance.

      OK, this is just a terminology gap then. Since terms like "object-oriented" and "v-table" were being used, I inferred the use of derived types and polymorphism via late binding of function calls. If that's not the case here -- I specifically ignored context, because I'm not a Linux kernel hacker -- then my argument isn't intended for this discussion. :-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    6. Re:But why should C++ be used in the Linux kernel? by Anonymous Coward · · Score: 0

      That and because std::sort() from the STL uses a different algorithm (shell sort?) than qsort() from the C stdlib (quicksort, obviously).

    7. Re:But why should C++ be used in the Linux kernel? by be-fan · · Score: 1

      IIRC, the STL uses a mix of quick, merge, and insertion sort depending on the size of the data. This gives it about a 50% advantage over the C library sort. What accounts for the rest of the difference is the exceedingly slow indirect call the C qsort() has to do.

      --
      A deep unwavering belief is a sure sign you're missing something...
    8. Re:But why should C++ be used in the Linux kernel? by iabervon · · Score: 1

      It has polymorphism via late binding of function calls, but the different implementations are independant of each other. I meant interfaces in the Java keyword sense (the set of methods an object of unknown exact type is known to support), not the more generic sense. That is, each type defines the v-table, and each implementation fills it in (subtypes are private and instances are generally produced by factory methods), using, if desired, some functions which give the "do nothing special" behavior.

  36. Windows kernel allows C++ by Anonymous Coward · · Score: 0


    While the NT kernel itself is written in C, and Microsoft doesn't officially support C++ for drivers, many people have figured out how to write Windows drivers in C++. It's about time Linux caught up!
    </troll>

  37. Sounds good...for some by Anonymous Coward · · Score: 0

    just don't try it on a 486 or for that matter a P1 or P2, unless you have gobs of ram and time to burn. Having smp with P1s or 2s might help. But how many cheapo multi-processors are still around? C might be out of date, but atleast it is quick.

  38. You're going to kill Stallman by TheKubrix · · Score: 2, Funny

    Or at least drive him (more?) insane!

  39. Reviving a joke... by ari_j · · Score: 2, Funny

    The good news is that we have a new renewable power source. What you do is wrap Linux in wires and place him in a magnetic casket. Putting C++ in the kernel will cause him to roll fast enough to generate enough electricity to power North America.

    1. Re:Reviving a joke... by That's+Unpossible! · · Score: 1

      (a) Linux is the OS. Linus is the man behind it.

      (b) He's not dead... yet.

      --
      Ironically, the word ironically is often used incorrectly.
    2. Re:Reviving a joke... by ari_j · · Score: 1

      You know what's really hilarious about that? Just before I made that post, I was bitching and thinking about making an AC post in response to someone who said "Linux" when they meant "Linus." Man, I hate hypoc...wait. Oops. ;)

      As to (b), do you really think he has anything to live for if his precious kernel is tainted with C++? I mean, family, hobbies, and other contributions to community and technology notwithstanding... ;)

  40. Oh god, WHY? by melted · · Score: 2, Interesting

    Haven't they read "Exceptional C++"? C++ is a fucking disaster. It kind of constantly conspires against you to shoot you in the foot in some kind of massive manner where you'd least expect. Sure, non-exception enabled code is ugly (check the return values all the time, etc), but any non-trivial exception-enabled code is nearly impossible to write if the requirement is that it works correctly in all situations (which is what the requirement is for the kernel).

    Don't get me wrong, C++ is an OK language, but I'd think twice before using its exceptions.

    1. Re:Oh god, WHY? by kraut · · Score: 1

      I'm not sure which "Exceptional C++" you've read, but non-trivial exception safe code (whichever guarantee you choose) is not that hard. And I'm pretty sure Herb Sutter would disagree that C++ is a disaster.

      There is more to learn than in C, yes, but it does give you a lot of benefit afterwards.

      --
      no taxation without representation!
  41. That's bull... by MouseR · · Score: 1, Informative

    thus making C++ exceptions viable in several scenarios

    By experience, C++ exceptions are the worse way of handling errors and leads to too many warp jumps that are difficult to track, trace and debug.

    C++ in a kernel is fine with me. But throwing exceptions in there is asking for trouble.

    1. Re:That's bull... by Anonymous Coward · · Score: 0

      By experience, C++ exceptions are the worse way of handling errors and leads to too many warp jumps that are difficult to track, trace and debug.

      In about a decade of using exceptions in various languages, I have not once needed to "track, trace and debug" them. The only thing I have ever wanted to see in the debugger is where the exception got thrown.

      In C++, when they do get thrown, the jump to exactly one place: the first handler that catches them. Whatever happens in between is the same cleanup code that should be running in equivalent C code as well, but is often forgotten by the programmer.

    2. Re:That's bull... by MouseR · · Score: 1

      And then some unsuspecting douf adds code that throws an exception that goes uncaught in a given condition and the whole thing blows.

    3. Re:That's bull... by Anonymous Coward · · Score: 0

      By experience, C++ exceptions are the worse way of handling errors and leads to too many warp jumps that are difficult to track, trace and debug.

      I disagree.


      C++ in a kernel is fine with me. But throwing exceptions in there is asking for trouble.


      Don't do that then. This article discusses kernel support (ie a speedup) for exceptions that will proably be thown in user space code.

    4. Re:That's bull... by Anonymous Coward · · Score: 0

      Unless you have a top level catch-all exception handler that prints out a debug stack trace and then let's you continue. Then you get a full understanding of where the exception occurred and know it never was processed correctly. With that, you can design your code *properly* so the exeception is handled in an appropriate place.

      All this exception bashing is tiresome. Error codes are not easier to read nor understand. An exception class is infinitely more readable.

  42. Mod Parent Up. by Vlion · · Score: 1

    This guy has seems quite correct.

    --
    /b
    |f(x)dx = F(b) - F(a)
    /a
  43. You do, apparently by Anonymous Coward · · Score: 0

    Haha! Now I'm a troll for dissing Linus!

    No, you're a troll for playing the victim before you get modded into oblivion.

  44. C++ in the kernel? by OverflowingBitBucket · · Score: 4, Insightful

    Now I'm a big fan of C++ and all, being both my language of choice and my favoured (or at least, least detested) language. However, there is the matter of using the right tool for the right job. When I need a quick, disposable tool, I don't fire up a new C++ file and work it into my project. I slap together something in ruby, and use that. Now, C++ in the Linux kernel?

    The value of an OO language in larger projects is enormous. Basically there are simply too many things that could go wrong at any point, and the overhead associated with C++ (memory use, exception setup, excess copying, dynamic checking) is a small price to pay for the additional benefits it provides. As you get closer to the metal though, and you have to watch what you are doing more closely. You want to know exactly when memory is being allocated, when something may go wrong, and only want to set up to catch exceptional circumstances if you know they may occur. Resources in kernel-land are expensive. C allows this kind of control, C++ does not.

    My former boss would love to see me defending C over C++ like this. The irony.

    Having said that, the capability to run C++ code in the kernel would certainly be nice, provided it didn't impact the existing code. I'm not sure how this one could be pulled off though. There'd be too much code that would need to be made aware of exceptions, destructors, so forth.

    1. Re:C++ in the kernel? by kraut · · Score: 1

      >C allows this kind of control, C++ does not.

      Err... can you show me anything that you can do in C that you can't do in C++? No one forces you to use any of the features you seem to find troublesome - you can be a "close to the metal" in C++ as in C. For starters, you could just recompile your C code with a C++ compiler ;)

      > (memory use, exception setup, excess copying, dynamic checking)
      Exceptions and dynamic checking are features that you choose to use if appropriate; they don't add overhead if you don't use them. One of the key design principles of C++.
      Memory use is not inherently higher in C++ than in C, and neither does the language force excess copying on you - that's more likely due to bad programming than the language.

      --
      no taxation without representation!
    2. Re:C++ in the kernel? by OverflowingBitBucket · · Score: 1

      Wish I had a bit more time to debate this (rotten tax return), so please excuse my brevity.

      > >C allows this kind of control, C++ does not.

      > Err... can you show me anything that you can do in C that you can't do in C++? No one forces you to use any of the features you seem to find troublesome - you can be a "close to the metal" in C++ as in C. For starters, you could just recompile your C code with a C++ compiler ;)

      Only use the C features in C++? Hehe, well, it goes without saying that they would be of comparable efficiency and use comparable resources then. A Bentley Arnage 4WD is just as fuel efficient as a Honda Insight if you leave them both stationary in a garage. I think the point of getting the C++ into the kernel is to use C++ features. The article talks about exceptions and dynamic type checking, so I think this is the case.

      If I had to answer your first question though (which is hard, C is (sorta-kinda) a subset of C++), I would probably mention that you can't just bolt on code in C++ using certain features (exceptions, global destructors) etc onto the C code base, whereas there are no such issues with C. Of course, you could limit the subset of C++ you use to C, in which case refer to the prior paragraph. Saying "let's use C++", and justifying potential problems with "we'll only use the C bits" isn't a terribly good argument; I presume you're not trying to do that?

      > > (memory use, exception setup, excess copying, dynamic checking)
      > Exceptions and dynamic checking are features that you choose to use if appropriate; they don't add overhead if you don't use them. One of the key design principles of C++.
      > Memory use is not inherently higher in C++ than in C, and neither does the language force excess copying on you - that's more likely due to bad programming than the language.

      I'm not sure I can effectively debate the first point, so I'll have to leave that to someone more knowledgeable in compiler development than myself. I do think that leaving out those two things would somewhat cripple C++. Bear in mind my comment about C++ being my favoured language, I'm not kidding about that. But I do stand by my assertion that there are places where it suits, and places where it does not.

      It is much easier to lose track of where and when memory is being allocated and calls are made in C++ than C. This is particularly true when using the STL. Unless you are advocating using C++ in the kernel without RTTI, templates, exceptions, constructors, destructors, so forth, in which case there isn't a lot of C++ left. :) Blaming inefficiencies on "bad programming" is like me saying anyone who doesn't like the way I cut my hair has "bad taste". It is particularly untrue for C++, which is (IMHO) harder to write optimised or deliberately controlled code for. I've lost count of the number of times I want to bust into one of the STL containers because I know it is going to go about things the slow way. Things are a lot more explicit in C, part of the reason why it doesn't scale too well (and I know I'll get shredded for that last sentence, but hey).

    3. Re:C++ in the kernel? by Anonymous Coward · · Score: 0

      You can apply C++ without pulling in the STL and the standard memory management. For the most part new can very easily be re-written (and I have done it in userland in order to demonstrate memory profiling and a couple other features that can be integrated in a transparent manner to the developer through control of memory management in C++).

      If you want to use new() in a kernel, then you make sure you are writing a custom new() function to manage the memory manually. You retain the same control, and new() can even be setup to simply jump into the kernel's normal MM routines, and new() gets inlined if you specify it to be so (when it is a mapping). The end result is that you have a lot of control over memory management, and everything else is built around that.

      A little understanding of the language specifications go a long way to be able to write good code for it, and avoiding constructs that don't make sense in a kernel environment (I don't see why you need an overloaded a==b for objects in a kernel environment...). I am not going to argue the exceptions point, as I think it would be problematic in a kernel, at best. You could write some sort of 'super-recovery' mechanism into the kernel which could recover in the case of some major uncaught exception... at least partly. Of course that is more theoretical, and not something I have time to experiment with. ;)

    4. Re:C++ in the kernel? by OverflowingBitBucket · · Score: 1

      > You can apply C++ without pulling in the STL and the standard memory management. For the most part new can very easily be re-written (and I have done it in userland in order to demonstrate memory profiling and a couple other features that can be integrated in a transparent manner to the developer through control of memory management in C++).

      Of course. Bringing in the STL would probably cause a lot of friction, for the reasons I have been discussing. And the "new" memory allocation absolutely must be changed... you can't use ordinary memory allocation functions in kernel-land. Also, how would you get the properties argument of kmalloc into new? Write a per-class new method? It would get messy fast.

      > A little understanding of the language specifications go a long way to be able to write good code for it,

      Of course. There is far less mystery in C though, and a fair bit more magic involved in C++, eg. in linking.

      > and avoiding constructs that don't make sense in a kernel environment (I don't see why you need an overloaded a==b for objects in a kernel environment...).

      Different people would see different benefits to different language features. I would for example not have such a problem with overloaded operators, you might, and everyone else would have their opinions too.

      > You could write some sort of 'super-recovery' mechanism into the kernel which could recover in the case of some major uncaught exception... at least partly. Of course that is more theoretical, and not something I have time to experiment with. ;)

      This might just raise the ire of those who really don't want C++-isms polluting the code. And the question begs, how would one go about writing such a beast?

    5. Re:C++ in the kernel? by OverflowingBitBucket · · Score: 1

      Sorry, s/kmalloc/kalloc/g.

    6. Re:C++ in the kernel? by alex_tibbles · · Score: 1

      "The value of an OO language in larger projects is enormous."
      And the kernel, at more than 4 MLOC isn't large enough?

    7. Re:C++ in the kernel? by OverflowingBitBucket · · Score: 1

      And the kernel, at more than 4 MLOC isn't large enough?

      A good point. :) Perhaps if one were to develop a Linux-like kernel from scratch, and we were prepared to tolerate potential C++ inefficiencies (eg. exception setup, see other posts) slipping through, we would see a kernel developed using considerably less resources and containing greater modularity than the present one. I'd wager that, once you got over the steeper C++ learning curve, that it was easier to develop for. It wouldn't be anywhere near as fast, but for the same effort it would probably have considerably more features.

      Unfortunately, this nice theoretical case looking at code size only isn't exactly what we have here. We have an architecture which requires careful and controlled use of resources. We also have (borrowing your estimate) 4 MLOC of mostly-C code already in use. Bolting on C++ code is going to add additional dependencies and resource requirements to the kernel. There would be some debate over which C++ features were considered acceptable. And in each case there are going to be people (justifiably) wanting to know what the benefit will be for the cost that must be paid.

      Having said all that, I think the use of additional languages in kernel and operating system code is inevitable, eventually. As processor power increases and hardware costs decrease, the limited resource argument becomes weaker and weaker. Eventually competitive pressure is going to push tools that are easier to use into development roles for these entities. My argument is merely "not yet". I expect to be wrong in x years, I just have no idea what x is.

    8. Re:C++ in the kernel? by Corngood · · Score: 1

      Also, how would you get the properties argument of kmalloc into new

      Overload it:

      new (GFP_KERNEL) SomeClass();

    9. Re:C++ in the kernel? by OverflowingBitBucket · · Score: 1

      Could I trouble you for some more detail on your suggestion? I may be unfamiliar with the technique you are trying to use and would rather not make an uninformed reply.

    10. Re:C++ in the kernel? by Corngood · · Score: 1

      Ok, sorry... you just define a new operator with extra parameters:
      void * operator new (int flags, size_t bytes) { return kmalloc(bytes, flags); } new (GFP_KERNEL) Foo();
      That would be a global one, you could also do it on a class basis. Also, I would probably write a safer wrapper like 'nothrow' in stdc++.

    11. Re:C++ in the kernel? by OverflowingBitBucket · · Score: 1

      Okay, thanks for the additional information. I have not used the placement syntax of new before (heck, I wasn't aware of it). For the curious, it lets you pass separate arguments to the allocator, even during construction, which does appear to solve the problem I originally mentioned reasonably well. My original implication that passing this flag would be difficult to do is thus incorrect. Corngood is quite correct.

    12. Re:C++ in the kernel? by BStorm · · Score: 1

      C++ does allow you as fine a degree of granularity when managing resources as C. The statement "As you get closer to the metal though, and you have to watch what you are doing more closely. You want to know exactly when memory is being allocated, when something may go wrong, and only want to set up to catch exceptional circumstances if you know they may occur. Resources in kernel-land are expensive. C allows this kind of control, C++ does not." is not necessarily a true statement.

      Memory and resource management can be made to do exactly what the kernel developer needs. Placement new and custom memory managers that replace the standard memory memory management will give the kernel developer precise control over where and how memory is managed.

      Classes and structs in C++ are abstractions with bindings to the correct function. With C++ a vtable is not required unless virtual functions are used.

      Templates can and should be used over macros when creating inline code. You have the benefit of typechecking. With use of Metaprogramming techniques tables that would have to be calculated during initialization can be created as a result of compiling the code (C++ Gems [Lippman 1997]).

      C++ allows the creation of higher level abstractions that operate close to the metal. I have seen and used C++ in a systems programming context.

      Your point about the existing kernel code and ensuring that coexists with the C++ written code is a point well taken. Until I review the kernel C++ code, I won't be in a position to comment about the impact on existing code.

      --
      Research is what I doing when I don't know what I am doing - Werner von Braun
    13. Re:C++ in the kernel? by OverflowingBitBucket · · Score: 1

      Wow, I never thought a post of mine would gather so many responses. :) I guess my original post must have been either insightful or inciteful. ;)

      C++ does allow you as fine a degree of granularity when managing resources as C. The statement "As you get closer to the metal though, and you have to watch what you are doing more closely. You want to know exactly when memory is being allocated, when something may go wrong, and only want to set up to catch exceptional circumstances if you know they may occur. Resources in kernel-land are expensive. C allows this kind of control, C++ does not." is not necessarily a true statement.

      Memory and resource management can be made to do exactly what the kernel developer needs. Placement new and custom memory managers that replace the standard memory memory management will give the kernel developer precise control over where and how memory is managed.

      Okay, I'll hit this from two angles. I both agree and disagree with you.

      On the memory management side, as Corngood highlighted earlier, you can explicitly specify allocation parameters when creating a new class. The notation is, IMHO, no more complex than the current C-equivalent. So from this angle, I agree.

      I do contend that C++ however does not have as explicit control over resource allocation as C does. When you add exceptions, virtual functions, global constructors, template instantiations and so forth, the C++ language expects the compiler to magically sort out the details and just make it work. It took some time for compilers to actually get this right, and different compilers achieve the magic required in different ways. C relies on considerably less magic, and is a less powerful language than say C++. Its advantage, however, is that whilst it is painfully explicit, it is painfully explicit. ;) I would contend that a language with less magic is a better fit to a problem where resource use and allocation must be tightly controlled. When you call a function in C, it runs and returns something (or longjmps over you, or exits). In C++, it runs, possibly throwing an exception, or maybe not. You can't be entirely sure how the exception will be handled... when do we push some return info on the stack, does the called function handle this, so forth. The general mystery (magic) is the problem to which I refer.

      Classes and structs in C++ are abstractions with bindings to the correct function. With C++ a vtable is not required unless virtual functions are used.

      Correct, they are not required, and probably won't be generated, and type information probably won't be generated. You are thus probably safe. I'm not sure if it mentions in the C++ standard if the compiler must not generate this information? Someone will surely point me to a mention here. In C though, you know you are safe.

      Templates can and should be used over macros when creating inline code. You have the benefit of typechecking. With use of Metaprogramming techniques tables that would have to be calculated during initialization can be created as a result of compiling the code (C++ Gems [Lippman 1997]).

      Templates do have strong benefits (eg. typechecking as you quote), although they are not without their problems. They tend not to behave too well relative to macros when you attempt to use features that fall outside of their scope... eg. explicit value initialisation, operations directly on the type name, so forth. And let's not forget the mess that is passing structures containing helper functions to a template as an argument. Additionally, error messages relating to template use tend to be absolutely hideous and undecipherable. And there is no standardised explicit initialisation. Templates are considerably easier to understand in source code form than macros though, and I do not deny the advantages that they bring.

      Thus I would disagree with the above statement being a general rule, but it is certainly a go

    14. Re:C++ in the kernel? by BStorm · · Score: 1

      This is where we digress.

      I do contend that C++ however does not have as explicit control over resource allocation as C does. When you add exceptions, virtual functions, global constructors, template instantiations and so forth, the C++ language expects the compiler to magically sort out the details and just make it work.

      Exception handling is scary, but the use of the longjmp is far more fraught with peril. Looking at my tattered copy of C: A Reference Manual, Fifth Edition, Samuel P. Harbison and Guy L. Steele Jr, it states that the behavior of longjmp is undefined if the argument to longjmp was not set correctly by setjmp. Since there is no explicit support in C to ensure that longjmp is used correctly. Most typical use is to call setjmp in a calling function and have the child function make a call to longjmp. There will be a resource leak because there is no release of resources allocate if a setjmp occurs. This is a trivial problem if the application terminates after processing a jmpbuf since all resouces allocated by the application are returned to the OS. There is no such safety net if the jmpbuf occurs within kernel/embedded system code. Consider the below code fragment (Please excuse my lack of indentation, I just couldn't get to work :):

      jmp_buf Err;

      int func main(int ac, int av){
      int status = setjmp(Err);
      if status != 0 then return status;
      process();
      return 0;
      }

      void process() {
      void *ptr = malloc(1024);
      longjmp(Err);
      free(ptr);
      }

      This kind of exception handling requires the adding of symbols to the global namespace with a real possibility of conflicts that will need resolution when libraries of code need to be merged.

      Exception handling provides a semantic framework for handling exception errors. It provides a well documented, if not well understood set of semantics for error handling. Consider the below code fragment:

      int func main(int ac, int av){
      try {
      process();
      } catch (...){ // handle the all the exceptions thrown by child
      return -1;
      }
      return 0;
      }
      void process() {
      try {
      void *ptr = new char(1024);
      throw
      } catch (...) {
      delete ptr;
      }
      }

      This illustrates that the when the exception is thrown the catch block is executed ensuring that any objects allocated from a resource pool (not including the stack) is freed. It is the responsibility of the developer to write the catch block resource management explicitly. What C++ standard and compliant implementation provides are the semantics and the framework for the developer to ensure that resource management is done.

      It took some time for compilers to actually get this right, and different compilers achieve the magic required in different ways.

      Granted different C++ compilers will generate different code to implement the specifics of C++ semantics. This is also true of C compilers generating different code to implement the specifics of C semantics. If the semantics are implemented differently and produce the expected results with no side-effects then they are functionally the same. It is also true that the run-time efficency will likely be a consideration in the selection of the C++ compiler but for linux is is for all intrinsic purposes it is the GNU C++ tool chain.

      C relies on considerably less magic, and is a less powerful language than say C++. Its advantage, however, is that whilst it is painfully explicit, it is painfully explicit. ;) I would contend that a language with less magic is a better fit to a problem where resource use and allocation must be tightly controlled.

      That is the same argument made 15 years ago that in order to develop a device driver you had to use assembly language. It would be prudent to code a C++ program that actually benchmarks some of the C++ language features that you

      --
      Research is what I doing when I don't know what I am doing - Werner von Braun
    15. Re:C++ in the kernel? by OverflowingBitBucket · · Score: 1

      You don't have to sell me on the benefits of using exceptions versus setjmp/longjmp. The majority of my software development is at the application level using C++, and as mentioned in my initial posting it is my favoured (least detested) language. I could provide very long-winded arguments for C++ over C at this level, and I'm sure you'd be backing me up. :)

      I feel the code fragments you've provided are a touch on the strawman side. You're asking for a comparison between C code specifically modelled around exception use, and C++ using exceptions. Between those two, the C++ solution is considerably more elegant. Realistically, the same code could be rewritten so that process has a return value indicating error return, with explicit cleanup of resources. With the C code you would know exactly what is cleaned up, and when. If you can cut certain corners, you may.

      Now forgive me for jumping a step along in the argument, but I presume a response to the above would be "What if there were (considerably) more resources to manage?". In this case the C code would maintain the advantage of explicit control, but would have the following disadvantages relative to C++:

      - considerably more complex resource management.
      - longer development cycle.
      - more repetitive code, thus a greater chance of introducing bugs.
      - harder to read and thus develop and debug for.

      You would agree? Now what would I rather write this in? C++ without a doubt. However, you do retain the explicitly control when using C. So there is a tradeoff: more control versus greater elegance.

      Granted different C++ compilers will generate different code to implement the specifics of C++ semantics. This is also true of C compilers generating different code to implement the specifics of C semantics. If the semantics are implemented differently and produce the expected results with no side-effects then they are functionally the same. It is also true that the run-time efficiency will likely be a consideration in the selection of the C++ compiler but for linux is is for all intrinsic purposes it is the GNU C++ tool chain.

      A single compiler toolchain makes things much easier. I couldn't really see C++ gain much ground if one had to argue the benefits across multiple toolchains. It would be a hard sell.

      That is the same argument made 15 years ago that in order to develop a device driver you had to use assembly language.

      And fifteen years ago it would have been a good argument. Resources were much tighter then. You wouldn't want to use this silly upstart C that doesn't explicitly let you set up your own call stacks and choose which arguments are held in which registers. Let a compiler choose which arguments will be kept in registers and which in memory without understanding the problem domain? Preposterous! ;) And here we are today debating letting C++ into the kernel. C is already a core part of the kernel, and the costs of letting the compiler decide register allocation and build its own stack frames is considered acceptable. As mentioned in another post on this topic, competitive pressure will push C++ into this role at some point. My argument is merely that it should not be today. C is a considerably more mature language than C++, both in terms of standardisation and compiler reliability. It wasn't that long ago that I was explicitly initialising global constructors in C++. I have just rewritten a chunk of code that used ifstreams back to use C FILEs to read data as the STL implementation included with the gcc of FC2 and mingw being too buggy to sensibly use (readsome() not working, eof() not returning true at end of file, in_avail() returning the wrong value, etc). I have found definite compiler bugs when using C++ (g++), but can't say the same about C (gcc). C++ is considerably more complex and younger than C. The instability of C++ is going to be a thorn for some time.

      It would be prudent to code a C++ program that actually bench

    16. Re:C++ in the kernel? by BStorm · · Score: 1


      The code fragments were indeed chosen to illustrate the elegance of C++ over C. Mea culpa:) The point that we seem to disagree on is whether elegance comes at the expense of explicit control. I believe that it does not, while you believe that it does.


      When there are features in a language implementation that do not work as expected, most developers develop an adversion to the language or create a work around that becomes an usage idiom. In either regard it will install a sense of distrust with the tool.


      It seems that we both agree that C++ eventually will become the development language of choice within the kernel.

      --
      Research is what I doing when I don't know what I am doing - Werner von Braun
  45. call/cc by Karma+Farmer · · Score: 2

    If we're going to add exceptions to the kernel, lets go all the way and add "call-with-current-continuation." Imagine how much cleaner the resulting code would be!

    1. Re:call/cc by Dr.+Photo · · Score: 4, Funny

      Clean, but not clean enough. For true conceptual purity, you need lexical closures, call-by-name, monads, lambdas, cooperative microthreads (though of course these could be simulated by call/cc), message passing, introspection and serialization, nongenerative record types, one-shot and partial continuations, maybe a little prototype-based OOP for flavor, and of course if you add prototype-based OOP, you'll need generics that are specializable by object rather than class (as well as consider the case of whether a method specialized for a particular prototype object still applies to its descendents), not to mention considering how that would affect the implementation of a meta-object protocol and multiple inheritance.

      Once you've done all this, Linux will truly be ready for the desktop. (Assuming you axiomatize your language definition first, to get rid of unnecessary features like for loops).

    2. Re:call/cc by Anonymous Coward · · Score: 0

      Why not just run a Lisp Machine and be done with it?

    3. Re:call/cc by 808140 · · Score: 1

      Wasn't that what we was suggesting? Not many languages other than LISP can boast all those features.

    4. Re:call/cc by Anonymous Coward · · Score: 0

      this stuff still makes my skin crawl. I remember a lecturer boasting about some toy language on a maspar machine "actually being faster than a C implementation!"
      Incredibly safe and secure and correct and why doesn't Boeing use it to fly planes?

    5. Re:call/cc by Piquan · · Score: 1

      Why not just run a Lisp Machine and be done with it?

      I don't remember ZetaLisp having call/cc, and I'm sure that ANSI CL doesn't.

    6. Re:call/cc by Anonymous Coward · · Score: 0

      And an internal database?

  46. Only a religious wacko by Anonymous Coward · · Score: 0

    would side with Israel, they can do no wrong in your fundamentalist mind, have a nice brainwashed life loser, it's the only one you get ;)

    1. Re:Only a religious wacko by Anonymous Coward · · Score: 0

      Yeah, I guess sending your children into Israel with bombs strapped to them is righteous (rolls eyes).

    2. Re:Only a religious wacko by Anonymous Coward · · Score: 0

      Actually, I'm having quite a nice life, thank you. And only a brainwashed loser would think that strapping a bomb to your chest and blowing up a bus full of civilians is a valid method of political expression.

    3. Re:Only a religious wacko by Anonymous Coward · · Score: 0

      Don't be stupid its only okay to blow up buses if they are full of Jews.

    4. Re:Only a religious wacko by Anonymous Coward · · Score: 0
      A truly fantastic conflict for opinionaters everywhere! After all this time, there are enough atrocities to go around that BOTH sides can feel self-righteous outrage in any argument.

      "You strap explosives to yourself and blow up kids on buses!"

      "You shoot unarmed children with helicopter gunships!"

      Repeat variations on these two themes over and over, and then revel in the moral darkness of your enemy. Never gets old!

    5. Re:Only a religious wacko by Anonymous Coward · · Score: 0

      Except that the Israelis try to avoid civilian casualties, the Palestinians try to inflict them. To the Palestinian terrorists any Israeli at all is a target.

      And look, it's working. Suicide bombings are way down. Only something like 3-5 in the past 8 months rather than weekly. The sooner the Hamas et al stop the sooner the Israelis will stop seeking them out, but Hamas et al have the stated goal of the destruction of Israel. They don't want peace, period.

      There's your moral high ground.

  47. That's not what exceptions are for... by Anonymous+Brave+Guy · · Score: 4, Insightful

    Sorry, but I think you're missing the point of exceptions. They are supposed to decouple generating the error from reacting to it, because in practice that's often useful.

    Exceptions are a systematic way to return control multiple layers up the code, without cluttering the code in between passing information it doesn't need to know or care about. They are best used where the code that directly causes the error can't handle it because it doesn't know how, and the code that handles it doesn't care where it came from, because the code that was trying to run aborted anyway.

    You could write at least a good length article on what exceptions are and aren't good for, but in short, if you ever throw exceptions exclusively at one level and catch them exclusively at the next level up, there's a good chance you're using the wrong tool for the wrong job.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    1. Re:That's not what exceptions are for... by AuMatar · · Score: 1
      They are supposed to decouple generating the error from reacting to it, because in practice that's often useful.


      In theory its useful. In practice its annoying and more difficult to maintain. Its a failed experiment.

      Exceptions are a systematic way to return control multiple layers up the code, without cluttering the code in between passing information it doesn't need to know or care about


      Umm, no. Exceptions are error codes passed as objects and with a wierd method of beign passed. They carry no less information than error codes. Its just as easy to pass up error codes by immediately returning on error, like this:

      error=readfile()
      if(error)
      return APPROPRIATE_ERROR_CODE

      Not too much information. In fact, it may well be more flexible- you can catch n error and return a different error code to the above level- changing perhaps from an OS file error code to an API level error, and do this up through n levels of API errors. With exceptions, the eventual catcher up 2 levels may not know what to do with a file exception- it may not even have known a file was in use. (Yes, you can emulate this functionality with exceptions by catching and throwing a new one, but that gets even uglier).
      --
      I still have more fans than freaks. WTF is wrong with you people?
    2. Re:That's not what exceptions are for... by lennarth · · Score: 1

      please do write that article on what exceptions are and aren't good for. I clearly understand exceptions now that I've read this comment of yours, and further knowledge would be real dandy.

    3. Re:That's not what exceptions are for... by Anonymous+Brave+Guy · · Score: 1
      In theory its useful. In practice its annoying and more difficult to maintain.

      That's what I used to think a long time ago. My mind started to change when I worked on my first million+ line project.

      Exceptions are error codes passed as objects and with a wierd method of beign passed. They carry no less information than error codes.

      I'm sorry, but that's staggeringly short-sighted. To give some obvious things you've ignored:

      1. Exceptions are typed and multiple types can be thrown from the same block in different circumstances.
      2. Exceptions can be constructed in a hierarchy, and derived exception types can be caught by base type.

      These introduce far more precision and flexibility into the process than a simple return code can, even without the distributed nature and potentially enormous amounts of boilerplate code they do away with.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    4. Re:That's not what exceptions are for... by AuMatar · · Score: 1
      That's what I used to think a long time ago. My mind started to change when I worked on my first million+ line project.


      Funnily enough, I started hating them when I saw them used in large projects. It just makes so much more sense to take care of errors immediately when you have a large project and the guy above you liek ly has no knowledge of your code.

      I'm sorry, but that's staggeringly short-sighted. To give some obvious things you've ignored:

      1. Exceptions are typed and multiple types can be thrown from the same block in different circumstances.
      2. Exceptions can be constructed in a hierarchy, and derived exception types can be caught by base type.


      And by the same token- an error code value corresponds to type of an exception. If you want multiple erros handled the same way, use the same block for multiple error codes.

      As for boilerplate code- not really. YOu use throw() instead of return and catch instead of a conditional. Same amount of code.
      --
      I still have more fans than freaks. WTF is wrong with you people?
    5. Re:That's not what exceptions are for... by Anonymous Coward · · Score: 0

      Exceptions in Delphi work well.

      All exceptions are derivatives from TException.

      So, along with Delphi's RTTI, you can do things like

      try
      blah
      except {catch some mythical exception of type TDBException}
      on (e: TDBException) do begin
      ShowMessage(format('Waah! %s\n',[e.description]);
      end;
      raise;
      end;

    6. Re:That's not what exceptions are for... by Anonymous+Brave+Guy · · Score: 1
      It just makes so much more sense to take care of errors immediately when you have a large project and the guy above you liek ly has no knowledge of your code.

      Fair enough; I guess it depends on how well-structured the project is.

      In my case, that first project I mentioned was very well designed, with clear levels of abstraction built on top of each other and good use of both functional decomposition and OO through those levels. If a hardware error was reported at the lowest levels, the action you wanted was frequently to abort the current operation, possibly with a quick tidy-up at low level to stop some hardware moving say, and then throw an error back up through the intermediate levels to the code handling the UI requests. If the hardware operation completed but the next level up decided the data was bad, it too would abort, and could do so using the same mechanism. This tends to happen quite naturally in code that has a clean, layered design. (Of course, not all large projects do, and maybe in other cases exceptions aren't as useful.)

      And by the same token- an error code value corresponds to type of an exception. If you want multiple erros handled the same way, use the same block for multiple error codes.

      If C++ had support for proper disjunctive types and pattern matching, I'd buy that. Since it doesn't, I just don't see how you can get the same degree of flexibility from a single return value of a fixed type.

      As for boilerplate code- not really. YOu use throw() instead of return and catch instead of a conditional. Same amount of code.

      If you're only throwing up one level, sure. One of my main points throughout this discussion has been that this isn't really a very good use of exceptions. Where they save is when you're throwing to five functions up the stack, and you don't have a constant stream of this sort of rubbish in every single function on the way:

      SuccessCode result = DoSomething();
      if (result == FAILURE) {
      return FAILURE;
      } else if (result == OTHER_FAILURE) {
      return OTHER_FAILURE;
      } else {
      DoSomethingElse();
      }

      IME, maintaining that sort of code in a large project is a recipe for disaster, but as always YMMV.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    7. Re:That's not what exceptions are for... by defile · · Score: 3, Informative

      Some people say exceptions. I say goto. Easy to understand, easy to implement, and very clean IMO:

      int addclient(int s,struct sockpair *sp)
      {
      struct sockaddr_in sin;
      socklen_t sl;
      int local,remote;

      sl = sizeof (struct sockaddr_in);
      if (-1 == (local = accept(s,(struct sockaddr *)&sin,&sl))) {
      perror("accept()");
      goto just_return;
      }
      fcntl(local,F_SETFL,O_NONBLOCK);

      if (extent >= TCPFWD_NO) {
      fprintf(stderr,"error: out of buckets! %u >= %u\n",extent,TCPFWD_NO);
      goto close_local;
      }

      if (-1 == (remote = socket(PF_INET,SOCK_STREAM,0))) {
      perror("socket()");
      goto close_local;
      }

      /* reuse sin struct from accept() */
      memset(&sin,0,sizeof (struct sockaddr));

      sin.sin_family = AF_INET;
      sin.sin_port = htons(remote_port);
      sin.sin_addr.s_addr = inet_addr(remote_addr);

      if (INADDR_NONE == sin.sin_addr.s_addr) {
      fprintf(stderr,"inet_addr('%s'): failed\n",remote_addr);
      goto close_remote_local;
      }
      if (-1 == connect(remote,(struct sockaddr *)&sin,
      sizeof (struct sockaddr_in))) {
      perror("connect()");
      goto close_remote_local;
      }
      fcntl(remote,F_SETFL,O_NONBLOCK);

      sp[extent].allocated = 1;
      sp[extent].a = local;
      sp[extent].b = remote;

      extent++;
      return 0;

      close_remote_local:
      close(remote);
      close_local:
      close(local);
      just_return:
      return -1;
      }

    8. Re:That's not what exceptions are for... by dcam · · Score: 1

      Exceptions are more controlled. When you have a catch block, it can only refer to the throw block above it, whereas with goto you open the door to jumping to that stop from anywhere on your code.

      You can do similar things with exceptions and gotos, but exceptions offer less chances to shoot yourself in the foot.

      --
      meh
    9. Re:That's not what exceptions are for... by Anonymous Coward · · Score: 0

      You can do similar things with exceptions and gotos, but exceptions offer less chances to shoot yourself in the foot.
      And they make sure you hit your foot instead of a ricochet off your toe and into your chest.

    10. Re:That's not what exceptions are for... by gnu-generation-one · · Score: 1
      sin.sin_family = AF_INET;
      sin.sin_port = htons(remote_port);
      sin.sin_addr.s_addr = inet_addr(remote_addr);
      Didn't SCO unix contain some code like that?
    11. Re:That's not what exceptions are for... by Anonymous Coward · · Score: 0

      I use the same idiom when I'm too lazy to convert primitive types into classes but you're mistaken here, what you really meant to say was "some people say automatic destructors, I say goto".

      If you replace all the gotos here with a return statement and turn "remote" and "local" to classes with constructors and destructors (and you rearrange the code so the variables are declared when used instead of all at the top), you get the same effect in C++ but it's much nicer and it has a lesser amount code. Plus you don't have to restrict yourself to this way of coding, you can have more complex nested block statements and stuff without managing the lifetime of anything.

      I don't come from the java school of thought where almost every function throws an exception instead of returning an error code. Infact, I disable exceptions and use error codes or code so I can silently ignore the error with no damage being done (i.e. basically do expensive NOPs). You'll find that most expert C++ programmers (that don't disable exceptions) model their behavior around only using them when their constructors fail and only when there is no way to recover from it.

      A good example of that is the file class in the C++ library. If if fails to open a file for reading/writing, all functions silently fail and return an error code, the constructor doesn't fail but you can check if it did by calling the function to test if the file is open.

    12. Re:That's not what exceptions are for... by Anonymous Coward · · Score: 0

      Its not just a "jump" that exceptions buy you, but also "state" by the "type" of exception, which also automatically associates the error with a specific cleanup handler for that specific type of error. Jumping out of one function block into another can easily get out of hand and crash your application due to the stack _not_ unwinding properly which throws off addressing for any local variables within the block of the new goto handler you might propose here. yes its stupid to jump out of context, but sometimes you have no choice!

      With exceptions you are guarenteed that the stack is managed consistantly, as well as allocations of local class instances on that stack that go out of scope. If no specific handler is defined for that exception then the error can be handled by a more generalized handler, or even throwing another for a cascade of cleanup handlers until the program gets to a place where the final, and more graceful shutdown or recovery can occure.

      A goto can not even return a simple error value! Can't use type auto or static because auto can go out of scope and static can be overwritten by another thread. Its just a _bad_ idea.

  48. about time by geg81 · · Score: 0

    C++ could help a lot making kernel development faster, making it easier to use more efficient data structures, and making it easier to avoid resource leaks, buffer overflows, and other problems. Whether or not this leads to any inefficiencies or code bloat in the kernel is up to the kernel developers; C++ has many faults and it fails to fix many of C's problems, but it does deliver on its main promise: you pay only for what you use.

    But in order to make C++ work in the kernel, the kernel developers need to stand behind it, set clear coding guidelines, and be committed to it. I don't see that yet.

  49. Linus and C++ in the kernel by noselasd · · Score: 4, Informative

    Linux made his view on C++ in the kernel a while ago here

    1. Re:Linus and C++ in the kernel by noselasd · · Score: 1

      Alright.. Linus* made his point. goddamn.

    2. Re:Linus and C++ in the kernel by Anonymous Coward · · Score: 0

      YEah... 12 YEARS ago!

      C++ WAS crap then. Things change and a decade is nearly a century of innovation and improvment in any other field.

      If Linus really thinks that C++ has no place in the kernel today becuase of a single incident 12 YEARS AGO, then I submit that he is getting a little too old and set in his ways to continue with this responsibility.

  50. C vs C++ by steinnes · · Score: 4, Insightful

    These guys didn't do this with hopes of it being accepted into mainline, they did it to use with their pronto project (some sort of dynamic multicasting project, using the Linux kernel).

    Personally, I think mixing C++ into the kernel is not a good idea, generally, in my experience certain aspects of C++ are messy to debug, and if you're gonna skip using them, then perhaps you should've stuck to C.

    Also these guys used to distribute their pronto project in one tarball, a modified version of the Linux kernel, and the website for downloading it made you have to accept *their* license. When the issue of whether this was possibly in violation of the GPL, and if they should rather distribute a clean patch, came up on the local GLUG mailing list (www.rglug.org) their response was rather shocking, they absolutely refused to acknowledge that they should perhaps distribute their code in another way, and even reverted to speculations about the legitimacy and enforcability of the GPL. To their defense, the original 'article' on the matter was very inflammatory and made some rather derogatory remarks, and IIRC they changed their website some time later.

    Multicasting is a cool technology, and dynamic multicasting routers such as RU is researching and developing with the Pronto project, may well be the key to using the internet as a single infrastructure for 95% of our content-delivery and communication needs (digital TV through the internet, without exponentially increasing bandwidth load, etc), so I hope RU keep on, and their work be fruitful :-)

    Also, to everyone who refers to the creator of Linux, as 'Linux'... his name is 'Linus', get it through your heads, this is slashdot.org not mouthbreathers.org ;-)

    1. Re:C vs C++ by halldorisak · · Score: 1

      Just to make it absolutely clear this C++ patch is free for everybody to use.

  51. Reality check by pslam · · Score: 2, Informative
    Nothing will come out of it, for the simple reason that C++ does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

    The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

    Put the strawman away. You don't absolutely have to use all the features C++ gives you if they aren't right for you. Don't use exceptions or run-time typing in an environment where you don't need it, or don't know if it'll work. Personally I never use either because I strongly disagree with the code they generate. If you don't understand that skilled usage of C++ generates exactly the same code that the equivalent C would (except the C++ took less time to type and checked your syntax better), you don't understand the point of C++ whatsoever. It's just a glorified type checking macro expander. And there's no reason to use plain C when you've got that at your disposal.

    Now have a look at examples of kernels written in C++. One easy example: Red Hat eCos. Just saying that C++ doesn't do kernels well doesn't remove the fact that people do use it in kernels, it works very well, and there are many examples out there.

  52. Re:"The fact is..." he's out of touch by mrsam · · Score: 0, Troll

    And, to add one more thing, nobody around here appears to have bothered to read what that fucking patch does anyway.

    It doesn't add C++ support to the kernel, you blithering slashbots.

    It adds native kernel support to C++ in userspace.

    Doh!

  53. Kernels for Dummies? by Proc6 · · Score: 1
    I've never c0d3r3d at that low level before, and while I have a basic idea of what the kernel is, can someone please post a quick For Dummies on kernel description and the advantages of something being "compiled into the kernel"?

    Beat me for my sub-geek intellectual prowess :(

    --

    I'm Rick James with mod points biatch!

  54. less snarky by pyrrho · · Score: 2, Insightful

    C++ is an extension of C... a continuation of it's ideals to see the machine as the machine sees itself, to allow the programmer latitude with the machine while giving ways for the programmer to protect itself from common problems.

    C++ is not distinct from C because it's evolution has been driven by adhering to the systems oriented philosophy of C and also by a very real effort to keep C++ "compatible" with C.

    Obviously, to take advantage of C++'s improvments, you have to learn and use them.

    --

    -pyrrho

    1. Re:less snarky by Anonymous Coward · · Score: 0

      a continuation of it's ideals
      it's evolution has been driven

      "its".

    2. Re:less snarky by ralatalo · · Score: 1

      an very real attept to keep C++ "compatable" with C...theer is valid C code which isn't valid C++ code as well was valid C code which is valid C++ code but means and works differently in C versus C++

  55. Just add my 2p by t_allardyce · · Score: 1

    C++ supports // comments! how can you pass that up? out of interest, what where the various versions of Windows written in? The kernel is pretty hardcore, and as much as C++ is fun and mature i don't see the need to taint that image of proper tried and tested built like a brick *nix reputation, really the kernel should be written in assembly (since its _ment_ to be for the x86) but c isn't too far off.

    --
    This comment does not represent the views or opinions of the user.
    1. Re:Just add my 2p by BubbleNOP · · Score: 1

      Linux kernel is portable to lots of platforms. It has very small portions in assembly. If it were written totally in assembly, it would be a pain to port.

    2. Re:Just add my 2p by Anonymous Coward · · Score: 0

      C++ supports // comments!

      So does ANSI C in the latest official version.

      i don't see the need to taint that image of proper tried and tested built like a brick *nix reputation,

      UNIX is "built like a brick" because so many people spend so much time debugging that. That is, it's working well despite being written in C, not because of it.

    3. Re:Just add my 2p by cant_get_a_good_nick · · Score: 1

      C++ supports // comments! how can you pass that up?
      I know this was a joke, but gcc has supported // for years. The newer versions of the C spec (I think starting with C99) has made this an official part of the language.

      i don't see the need to taint that image of proper tried and tested built like a brick *nix reputation, really the kernel should be written in assembly (since its _ment_ to be for the x86) but c isn't too far off.
      C actually was created to make UNIX more portable. C was created to do all the higher level parts of UNIX, and only the really fast bits needed to be assembler. At the time, there was a lot more diversity in machine hardware, and having it written in assembler would have very much slowed its early growth.
      Yes, Linux started on the x86 line, mostly as an excuse for Linus to hack around with the 386's new features, but it's on many architectures now. Targetting even solely x86 now would be a challenge, since there are so many x86's to choose from. Do you really want to spend time hand tuning your assembler to perform well both on plain 386 machines, and OOO and Pentium4 HT units? Or do you say the compiler people can deal with this tuning crap and you can get your work done.

    4. Re:Just add my 2p by t_allardyce · · Score: 1

      I ment the reputation it has as being written in a hardcore language that people associate with machoness hence like a brick, if it was written in BASIC for example...

      --
      This comment does not represent the views or opinions of the user.
    5. Re:Just add my 2p by t_allardyce · · Score: 1

      Translated that means we wouldnt be able to have sexy looking Linux PDAs..

      --
      This comment does not represent the views or opinions of the user.
  56. Re:"The fact is..." he's out of touch by devphil · · Score: 1


    Exactly. This is a Good Thing.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
  57. c++ in the kernel by joxeanpiti · · Score: 0

    This is a sacrilegy

  58. Re:"The fact is..." he's out of touch by Abcd1234 · · Score: 1

    It doesn't add C++ support to the kernel, you blithering slashbots.

    Really... well, to quote the article:

    In particular our run-time support enables the full use of C++ exceptions in the Linux kernel

    Programmers that have used C++ in Linux kernel modules

    Exceptional Kernel: Using C++ exceptions in the Linux kernel

    So, you were saying?

  59. Re:"The fact is..." he's out of touch by lennarth · · Score: 1

    it would be interesting to read a paper that discusses C++ compilers and their trustworthiness.

  60. C++ in embedded applications is a bad idea by amightywind · · Score: 3, Insightful

    Embedded dev is now often C++ based.

    Too bad too. I am developing FAA Level A avionics software using C++, I am sorry to say. What a debocle. For starters, the compilers for non-gcc supported platforms uniformly suck. Typical compilers for DSP's lag the C++ standard by 10 years, and crash frequently. And my project is proof that if a language feature exists it will be used, no matter how pointless. For example:

    /* Rational person sets a control register in C */
    *SOMEREG_ptr = BIT_A | BIT_B;

    or

    // C++, is this really better?
    Register_set<std::uint16_t> regset(base_address);
    regset.write(SOMEREG_OFFSET , Register_set<>::BIT_A | Register_set<>::BIT_B);

    Gross. Please keep C++ out of the Linux kernel!

    --
    an ill wind that blows no good
    1. Re:C++ in embedded applications is a bad idea by geg81 · · Score: 0, Flamebait

      Both your C and your C++ code absolutely suck. It's scary to think they let you anywhere near avionics of any type.

    2. Re:C++ in embedded applications is a bad idea by Anonymous Coward · · Score: 0

      Just curious as to what you would change with
      *SOMEREG_ptr = BIT_A | BIT_B;

    3. Re:C++ in embedded applications is a bad idea by Anonymous Coward · · Score: 0

      Kinda looks like the author wanted to set 2 bits of the register. Perhaps the whiner assumed they wanted to leave the rest of the register alone, and then the proper statement would be:
      *SOMEREG_ptr = *SOMEREG_ptr | BIT_A | BIT_B;

      Iif you want to zero both bits:
      *SOMEREG_ptr = *SOMEREG_ptr & ~BIT_A & ~BIT_B;

    4. Re:C++ in embedded applications is a bad idea by Anonymous Coward · · Score: 0

      I also happen to work on Avionics software, doing testing under a military standard, and the code is horrible. I'm rather scared to get on an airplane now that I see how bad it is.

    5. Re:C++ in embedded applications is a bad idea by cheekyboy · · Score: 1

      So tell me why would any coder with >10 years experience would ever use that long complex C++ code to set a bit ???

      I would still use "*SOMEREG_ptr = BIT_A | BIT_B;" in C++, but perhaps it could be easier to do that in a virtual fuction called "SetValue()", at least then the code is more pretty and can be changed easier later.

      The whole point of C++ is to have objects with members/classes of isolated functions. No one is saying , "hey bob, now that its c++, use all the wierd shit you can find" , jeez, if they do that , then REMOVE them from any project.

      My rule of thumb is, still use C style coding, but inside C++ usefull layers/classes. Only a complete nerd/dill brain would use your C++ sample there.

      But still there are complete pointless ways to do stuff in C too that can be bloody ugly and horendous.

      --
      Liberty freedom are no1, not dicks in suits.
    6. Re:C++ in embedded applications is a bad idea by builderbob_nz · · Score: 1
      Class templates aside (my C++ is rusty, I think that was a template), wouldn't this be better? (Asume you have a special class for handling these bit registers)
      myBitRegister.Set(BIT_A);
      myBitRegister.Set(BIT_B );
      Unless you absolutely must have every single CPU cycle doing something useful, then why not keep it easy to read and understand?
      --

      Karma? Hey I just call it as I see it.
    7. Re:C++ in embedded applications is a bad idea by Anonymous Coward · · Score: 0

      Please remind me never to fly with anything that has your company's products inside, since it's obvious you don't know what you are doing.

    8. Re:C++ in embedded applications is a bad idea by Anonymous Coward · · Score: 0

      Ada
      Ada mention
      You won't be alone.
      Once you get over the ugly syntax, you'll really like Ada.

    9. Re:C++ in embedded applications is a bad idea by kahei · · Score: 1


      The correct way to do that in C++, as I suspect you know deep down inside, is: /* Rational person sets a control register in C++ */
      *SOMEREG_ptr = BIT_A | BIT_B;

      If you accept the code of drooling idiots, you will have code like your second example.

      Moral: do not employ drooling idiots (or fresh CS graduates)

      --
      Whence? Hence. Whither? Thither.
    10. Re:C++ in embedded applications is a bad idea by Anonymous Coward · · Score: 0

      Too bad too. I am developing FAA Level A avionics software using C++....

      I'll take the train...

    11. Re:C++ in embedded applications is a bad idea by geg81 · · Score: 1
      The code treats I/O operations just like any other pointer update instead of defining an accessor for the hardware. It also seems to use Hungarian notation ("..._ptr").

      A saner thing in both C and C++ is to write
      io_set_SOMEREG(BIT_A|BIT_B);
      In C, this can be a macro, in C++, an inline function. It doesn't cost you anything to do that in terms of performance, but it documents what is going on, it lets you trace and/or debug things, it makes it easier to port the code to new hardware, it lets you add debugging code and/or assertions, etc. Internally, "io_set_SOMEREG" can then be as gross as you like.

      Furthermore, if the register really is a "uint16_t", like the C++ code indicates, there should be an explicit cast to that effect in the C code, because whatever compiler he may be using, an "int" is not going to be the same as a "unit16_t".

      The comparison is also bogus because the guy didn't even show how he got SOMEREG_ptr, which is a pretty gross operation in C as well.

      For the C++ code, using "typedef" and "using" would help with the notational problems the programmer seems to be having, as in
      typedef Register_set<std::uint16_t> RegisterSet16;
      In fact, several languages force programmers to create typedefs for every template instantiation, presumably to avoid messes like this guy is creating.

      But that's not the worst of it. Rather, he puts all the complexities of template classes into his code and still scatters offsets and hardware updates in places where they don't seem to belong. A better thing is to actually define an object that encapsulates the hardware:
      class AirplaneHardware {
      public:
      void enable_fuel_pump();
      void disable_fuel_pump();
      }
      That's actually much closer to what a sane C programmer might have written historically: he might have defined a C structure representing the hardware register set and updated registers through that.

      So, the C++ code would look like:
      hardware.enable_fuel_pump();
      And that is indeed better than
      *SOMEREG_ptr = BIT_A|BIT_B;
    12. Re:C++ in embedded applications is a bad idea by Anonymous Coward · · Score: 0

      Who can tell? The C code is so poorly written and documented that it may be a bug or it may be what he wanted.

    13. Re:C++ in embedded applications is a bad idea by rxmd · · Score: 1
      I am developing FAA Level A avionics software using C++, I am sorry to say.
      Dilbert: Hey Wally, I hear that in the backend software for our nation's new air traffic control system, you reused code from the payroll system. Is that true?

      Wally: Here's a tip: Don't fly on pay day.

      --
      As a state gets corrupt, its laws multiply; the most corrupt states have the most numerous laws. (Tacitus, Annales 3:27)
    14. Re:C++ in embedded applications is a bad idea by amightywind · · Score: 1

      Unless you absolutely must have every single CPU cycle doing something useful, then why not keep it easy to read and understand?

      Because in embedded applications you absolutely must have every CPU cycle doing something useful. Absolute efficiency drives down the cost of the processor your have to buy, or drives up the amount of functionality you can fit on a processor. If you had embedded experience you would know that.

      --
      an ill wind that blows no good
    15. Re:C++ in embedded applications is a bad idea by amightywind · · Score: 1

      So tell me why would any coder with >10 years experience would ever use that long complex C++ code to set a bit ???

      I didn't say I wrote it. It is what is used here by 50 developers and I can't change it. You bring up a good point though. The second example was developed by some smart, experienced people. My point is that C++'s huge complexity encourages otherwise intelligent developers to create overwrought designs. I have seen it again and again in projects. You even see it in diversity of proposed solutions in the replies to my original post. We are talking about setting bits in an integer! One processor instruction!

      --
      an ill wind that blows no good
    16. Re:C++ in embedded applications is a bad idea by Christov · · Score: 1

      Umm, for which aircraft?

      so that I might avoid them.

      Seriously, avionics is what Ada was invented for. This loony love of C++ at corporate levels is going to get people killed. Well, FAA certification requires provably correct code, but there are other embedded scenarios that could be dangerous.

  61. Shouldn't that be... by gatkinso · · Score: 1

    ... your 0.02 CENT?

    --
    I am very small, utmostly microscopic.
    1. Re:Shouldn't that be... by Anonymous Coward · · Score: 0

      ...only if Euro = CENT
      a better exhange for 0.02 Euro would be 2 Cent

    2. Re:Shouldn't that be... by Anonymous Coward · · Score: 0
      Not unless they have introduced new 1/5000 Euro demonination curreny.

      Perhaps you were thinking of 2.00 cents ;)

    3. Re:Shouldn't that be... by grozzie2 · · Score: 1
      no. 0.02 EURO is 0.03 CENT...

      Take a good look, the buck isn't worth the paper it's printed on anymore....

    4. Re:Shouldn't that be... by orcrist · · Score: 1

      no. 0.02 EURO is 0.03 CENT...

      Wow!!! Did the Euro crash? Last I saw 0.02 EURO was more like 2.54 U.S. CENTS which would round to 0.03 U.S. DOLLARS ;-)

      -chris

      p.s. Euro also has cents, so 'CENTS' has to be qualified anyway.

      --
      San Francisco values: compassion, tolerance, respect, intelligence
  62. Dumb Person... by polyp2000 · · Score: 1

    anyone care to explain in reasonable level terms what having runtime level C++ support in the linus kernel actually means?

    Whats the issue ?

    nick...

    --
    Electronic Music Made Using Linux http://soundcloud.com/polyp
    1. Re:Dumb Person... by pclminion · · Score: 1
      C++ depends on some external functionality, which is assumed to be provided by the runtime environment. The most obvious examples are exception handling and the code which invokes global object constructors/destructors. On Linux/G++, this is provided by the libg++ library, and it integrates tightly with theC runtime. All C++ programs which use exceptions or any other C++ built-in functionality (like implicit copy constructors, etc.) depend on this library.

      In order to support C++ code in the Linux kernel, the equivalent functionality must be coded in a way which is compatible with the kernel environment. libg++, for example, won't work in kernel space, because it is vastly different than user space.

    2. Re:Dumb Person... by rjh · · Score: 5, Insightful

      First, you're not dumb; you just don't know much about the issue. Which is good: it means you know a lot more than a lot of the people who have been responding so far.

      Essentially, C++ offers support for many, many different types of programming. Just like there are some tasks for which object-orientation is better than procedural, there are some projects for which generics are superior, for which functional programming is superior, etc., etc.

      C++ is not an object-oriented language and was never intended to be (as reading Stroustrup will tell you); C++ was meant to support a broad variety of programming styles, of which object-oriented programming is just one.

      So what do we gain by allowing the kernel to use C++? Mostly, we allow kernel programmers flexibility to solve problems in different ways. However, the trick to this is that while we're giving the programmers additional tools with which to do their jobs, we're giving them more complex tools which sometimes fail in extremely bad ways.

      Exceptions are a good example. Up until very recently, code that used exceptions was about 5% slower than code that was exception-free. This five percent penalty was unavoidable overhead. Now, some people got bit by this five percent hit (usually people working in realtime fields) and came to the conclusion of "oh, C++ sucks for RTOS because exceptions give a five percent hit".

      The reason why they came to that conclusion is easy to understand: it's easier to blame their tool than their knowledge of the tool. It's easy to say "oh, C++ sucks"; it's harder on the ego to say "well, I didn't know that about C++, and it bit me in the ass."

      Many--and maybe most--people who condemn C++ have not used it recently. Linus, for instance, condemns C++ based on his experiences with it from 1992, six years before the C++ language had been standardized and ten years before GNU got a decent C++ compiler.

      C++ is a very complex language, as anyone, even C++ aficionados, will tell you. On the other hand, in the hands of someone who's made the (significant) investment to become a skilled C++ programmer, C++ is capable of breathtaking power and elegance.

      The conflict is essentially this: one side believes "if we add C++ support to the kernel, we'll have lots of incompetent C++ people doing all manner of incompetent C++ things which are really stupid and killing performance" and the other believes "with C++ support to the kernel, we give programmers different ways to solve approach problems, and I'm not going to deny all programmers the benefit of C++ just because many programmers can't use it effectively."

      I sincerely think that adding C++ support to the kernel is a good idea, subject to some strict requirements. For instance, have a C++ Czar for the kernel, someone Linus trusts to have wisdom and understanding of C++; and make sure that all C++ checkins to the kernel go through the C++ Czar to ensure that C++ is being used wisely, and not as an impediment to understanding.

    3. Re:Dumb Person... by Anonymous Coward · · Score: 0

      Let me know when you meet one of these mythical competent C++ programmers. Stroustrup isn't one (have you read Stroustrup's code? It's frequently unreadable nonsense)

      I've never seen any of this breaktaking power and elegance from C++, but I have seen plenty of confusing and bizarre structures clearly invented from whole cloth by someone who wanted to keep their job ("Let's see them replace me now, they'll never untangle this mess").

      If you really wanted breathtaking power and elegance you want LISP or something, not a C look-a-like with essay-length keywords.

      In practice about 1% of today's C++ code ought to have just been C, and the remaining 99% should never have been solved in a full-blown native compiled language in the first place. Much of that 99% shouldn't have been in a programming language of any kind (should have been done in a purpose built database schema language, GUI design language, etc.) and the rest should have been glue code in Java, Python, or some other safe extensible platform neutral language.

      But of course it's cheaper to hire one semi-competent C++ hacker who bodges things together than to hire half a dozen specialists who'll build what you really needed. You know in the UK the government funded, national database of jobs doesn't know the difference between C and C++? It describes this skill as "C/C++ programmer" as though they were one and the same

    4. Re:Dumb Person... by genneth · · Score: 1

      This is one of the more insightful comments in this whole torpid flame war. Those who think that C++ is a broken language, check out Boost, which are a set of extensions to the STL (and sometimes fixes -- these are the people who will change the C++ standard in future). Those who think that C++ is nirvana for the soul, check out the past attempts by the same experts (I sincerely believe that there are no other people in the world who can write C++ to the same standard). I personally like to use whatever language is best suited, and that means suited to me as well as to the project. Often, dotNET (I use Mono, so don't killed me, mods...) might be a technically better solution, but I will go with Python simply because I have more experience with it. Therefore, on this issue I am undecided. Someone else has already pointed out that our current kernel developers are quite C orientated, which means that they won't be as clued up on C++ patterns + idioms than someone who dreams about metatemplate programming. There are a lot of things that can go right with putting C++ in the kernel, but a seriously large amount that can go wrong as well.

    5. Re:Dumb Person... by Anonymous Coward · · Score: 0

      So you were working with Stroustrup auditing all the C++ code out there, and you conclude that all that code must be blown.

      Well, i wonder what were you smoking...

  63. So now we only have to teach Linus C++... by Anonymous Coward · · Score: 0

    and he'll start throwing exceptions all around the place like crazy...

  64. (A discent:) Oh dear, again someone who... by IBitOBear · · Score: 1

    ...is prone to abstruse and glittering generalities.

    One must only be *consistent* in one's use of exceptions. I (occasionally) write exception heavy code. That doesn't lead to the proposition that exceptions only exist to defend against things that should "never, ever happen."

    Exceptions exist to remove redundant (and so error-prone) checks. If a tree branch is twenty-steps deep, and each step must check the return code on the branch for the error case and handle it and then propigate it back towards its caller, then you nave nineteen redundant code actions and so nineteen opportunities for someone to make a (compundable) mistake in handling the error.

    The C++ exception mechanisim provides a means for the compiler to generate all the code to Do The Right Thing(tm) automatically and without _unnecessary_ programmer interaction.

    The short version is that if all you classes (objects) do proper semantic cleanup on destruction, and all your call frames are exception safe in their handling of intermediate state, then stack-unwinding *is* proper semantic cleanup. When something more than cleanup is needed, there, and only there, is where you catch the exceptions. This leads to only having to write the error _handling_ code once, in the proper and meaningful context.

    The fact that C++ exceptions throw fully-fleshed objects means that the exception itself can communicate more than its mere existence, which makes it even more useful. (I will skip the digression here, but I have used excpetions to "return" references to offending objects into contexts where they can be dealt with, with great success, and without having to burden call semantics for intervening frames. It's an incredibly powerful and readable technique.)

    The fact that _many_ programmers "are bad" and don't otherwise maintian "semantic invariants" in their objects; allocate "bare" pointers; and catch exceptions by value instead of reference leads to a lot of people writing marginal exception-based code that is *terrible* and unsustainable. But that is bad art, not bad facility. I have seen similarly disasterous choices in every language I have ever been exposed too. (It's a poor craftsman who blames his tools. 8-)

    So what?

    A lot of people injure themselves using nail-guns each year, which is not a argument against construction equipment, it's just an argument against incompetence.

    The sole point of contention is whether the "error" must be an _ERROR_ or if it is sufficent for the "error" to "just" be a "sufficently exceptional condition" to merrit a non-local return.

    At least it's not setjump/longjump... 8-)

    Personally, I anchor the root of my exception class hierarchy on Exception ==> Fault and Exception ==> Error, with classical errors branched off of "Error" and semantic errors based off of "Fault". I then crash-proof by catching any Excpetion by reference in the last recoverable frame before semantic collapse. (This protects against "unexpected" and other stupid mistakes to which even I, in my infinite wisdom, are subject. 8-)

    For instance consider Fault ==> LockFault. I throw a LockFault whenever you/I mess up a lock (unlock a lock you don't hold or "try" a lock and fail to get it). These semantic errors are "common enough" but still deserving of exception status. The LockFault lets me "back off" from deadlocks automatically because I A) hold locks via objects so the destructors release locks during stack unwinding and B) I can catch lock faults in a context where a retry makes sense instead of passing-out state itteratively. This then leaves me "ready to act" in a semnatic frame where a retry can be logically attempted (as opposed to mechanically attempted) in a rational and reasonable manner.

    Further, these locking layers are managing real (unpulgable) devices and real (droppable) network connections. The braided exceptions path is, at first, complex, but after a very-short period of annalysis makes sense, as all three semantic fa

    --
    Innocent people shouldn't be forced to pay for inferior software development.
    --"Code Complete" Microsoft Press
  65. (d) There's a big fat hole in the standard. by Ungrounded+Lightning · · Score: 2, Interesting

    My pet peve: the gaping hole in the standard regarding the use of virtual functions from constructors and destructors and routines that serve them.

    If a member object's constructor, or a routine it calls, somehow gets hold of a pointer to the containing object and calls a virtual function, IMHO it should be performing a legal operation and should get the BASE CLASS version of the function. Ditto in the destructor. (At this stage of construction the base class is fully functional, while the derived class is not yet initialized making attempts to call its version of the function massively broken.) Ditto during destruction. The derived class version should be the one you get beginning with the first line of the body code of the constructor and ending with the last line of the body code of the destructor. (The object transitions during those sections of code, which can be coded carefully to only use virtual member functions whose support is initialized.)

    Everywhere else C++ uses extreme care to get the "right" level of virtual function. (This is unlike Objective C and Smalltalk, which "get it wrong" big time by calling derived class (subclass) versions in base class (superclass) construction code, breaking the already-debugged code.) But here the standards - and the implementors - missed an imporatant point.

    With an opportunity for both construction and destruction code to get it "right" (call the base class version) or" wrong" separately you have four binary combinations - of which one is "right" and three "wrong". In the early days (pre-standard), cfront got it "wrong" one way, gcc another way, and three commercial compilers for PCs the third way. (So the standard would have imposed equal pain by prescribing the "right" way, leaving them all "broken".) But the first ANSII standard explicitly left it undefined, while the second one not only affirmed that but explicitly warned against calling virtual functions from constructors and destructors.

    (I did bring this up with the committee both times, but was unable to sway them, even to make it a recommendation or to provide a "pedantic construction/destruction order" switch.)

    Getting it "right" would have had considerable benefits. There's a lot of useful things (which I won't go into here) that become easy if it's "right" and breaks badly - or requires combersome workarounds - if it's "wrong". And getting it "wrong" also leads to subtle bugs and interactions even if you're NOT trying to do something fancy.

    (Because it was "wrong" in all the compilers and not forced by the standard, a large programming project I was working on back then was forced into workarounds that gutted the opportunities to build complex objects using member objects, replacing them with smalltalk-style heap-allocated objects strung together by pointers (with enormous overhead as a reault) and creating an initialization function hierarchy parallel to the construction hierarchy to get things properly spun up.

    In the kernel the code must be solid and really should be tight and do things the obvious and simple way. So a feature-gutting, bug-attracting, spec ambiguity like this is a nightmare.

    Thus for me:

    * (d) There's a big fat hole in the standard.

    Is a killer.

    --
    Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
    1. Re:(d) There's a big fat hole in the standard. by Ungrounded+Lightning · · Score: 2, Interesting

      Everywhere else C++ uses extreme care to get the "right" level of virtual function.

      (Or overridden functions in general, whether virtual or not.)

      --
      Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
    2. Re:(d) There's a big fat hole in the standard. by Abcd1234 · · Score: 1

      This is unlike Objective C and Smalltalk, which "get it wrong" big time by calling derived class (subclass) versions in base class (superclass) construction code, breaking the already-debugged code.

      I'm kind of curious what you mean by this. First off, there there no constructors in Objective-C and Smalltalk. In both languages, you have "init" functions which serve to initialize an allocated object, but these are no different from any other message. They just happen to set fields and do other initialization tasks. So, in Smalltalk, I do something like this:

      obj := [MySubClass newWithValue: 5]

      Where newWithValue is defined in MyClass. Now, if I understand you correctly, your problem is that, if newWithValue: is defined as:

      newWithValue: aValue
      obj := [self new].
      [obj setField: aValue].
      ^ obj.

      and MySubClass overrides setField:, then the subclass' version is called, rather than the superclass. Correct?

      Now, my response to this is: newWithValue is *nothing special*. It has no special semantics that make it different from other messages. As such, the message setField: called inside newWithValue: is no different than an external entity calling setField: directly. And in the latter case, you expect the subclass implementation to be called, and as such, you should expect the same from the "constructor".

      So, what I'm wondering is, what's "wrong" about this? To me, it seems like the height of consistency, especially when you understand that newWithValue: is just like any other message. As such, it's simply up to the programmer to avoid doing something stupid.

    3. Re:(d) There's a big fat hole in the standard. by Ungrounded+Lightning · · Score: 1

      Now, my response to this is: newWithValue is *nothing special*. It has no special semantics that make it different from other messages. As such, the message setField: called inside newWithValue: is no different than an external entity calling setField: directly. And in the latter case, you expect the subclass implementation to be called, and as such, you should expect the same from the "constructor".

      So, what I'm wondering is, what's "wrong" about this? To me, it seems like the height of consistency, especially when you understand that newWithValue: is just like any other message. As such, it's simply up to the programmer to avoid doing something stupid.


      Yep, it's "wrong". Here's the reason:

      The init functions are executed from base (super) toward derived (sub) classes. If the derived class version of the funciton requires the init at its level to have been run in order to perform correctly, being called due to the execution of a baseward init before the derived class init runs breaks the code.

      An example of ways this happens is when one of the lower levels of your class hierarchy links the instance you're constructing/initting into a list of all instances of this class tree, the overridden function is one that is used by external clients which run the list (to obtain the correct flavor of activity for each subclass instance), and such running of the list and calling of the function may be provoked by a side-effect of the construction/initialization or by an external asynchronous event (such as the arrival of a message or a screen refresh). The baseward function might be a no-op while the derived class version performs a job that requires initialization to be complete - at least to its level.

      At the time we first encountered this issue, it broke us for two things we wanted to to.

      One was garbage collection: The overridden function gave a list of the pointers at this and lower levels for the garbage collector to follow. If something called during construction did memory allocation it might provoke the garbage collector to start. If the devived class version of the function was called, the garbage collector would follow uninitialized pointers. Of course any disturbance (such as adding instrumentation to try to find out what was going wrong) would result in different memory allocation causing the garbage collection to happen at a different stage of execution. Thus a heisenbug.

      The other was exception handling: At the time "catch" and "throw" were reserved words in the language specification, so we wrote out own routines. A large fraction of exceptions would be the result of problems during construction that would requrie the abortion of the construction and the destruction of the object to free resources siezed at lower levels. The destructor was also virtual, so calling it would get the correct destruction routines called ONLY IF you got exactly the deepest level where construction had already occurred. Because of the ambiguity in C++ we couldn't throw such exceptions from member objects because (depending on the compiler) they might run the current-level destructor when the corresponding constructor had not run, so the destructor would be operating from uninitialized variables. Trying to hack up the equivalent in Objective C or Smalltalk would result in ALL the levels of the destructor-equivalent being run, regardless of the level of construction/init achieved before the exception. (Of course Smalltalk dosen't itself have the concept of termination, since the deallocation mechanism is to "lose" the object, but that's a separate issue.)

      Our workaround at the time was to completely eschew member objects with non-trivial behavior on construction/destruction. Instead we used only pointers to them, allocating them on the heap in the constructor after the member variables that would point to them were initialized to null. This resulted in enormous extra memory management overhead and turned the data structure into a Smalltalk-style mass of l

      --
      Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
  66. C++ is a waste of time by Anonymous Coward · · Score: 0

    People should instead jump to JAVA, and write te whole of it in Java!!!

  67. getting ready with popcorn by szo · · Score: 1

    and waiting for Linus to flame them into oblivion...

    --
    Red Leader Standing By!
  68. Phew, good we're rid of that by fleblebleb · · Score: 1

    From the patch: +/* Define to 1 if installation paths should be looked up in Windows32 + Registry. Ignored on non windows32 hosts. */ +/* #undef ENABLE_WIN32_REGISTRY */

  69. No matter how low your opinion of Portland ... by Ungrounded+Lightning · · Score: 0, Offtopic

    Linus is rolling in his grave.

    No matter how low your opinion of Portland, moving there is NOT as bad as dying.

    --
    Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
  70. I care by geg81 · · Score: 1

    The fact is, C++ compilers are not trustworthy.

    Neither are C programmers. But unlike C programmers, who keep making the same mistakes generation after generation, C++ compilers are actually getting better with time.

    any compiler or language that likes to hide things like memory allocations behind your back just isn't a good choice for a kernel.

    But C++ doesn't hide memory allocation behind anybody's back. You get to decide exactly where memory allocation happens and where it doesn't.

    * you can write object-oriented code (useful for filesystems etc) in C, _without_ the crap that is C++.

    Yes, because it is so much "better" to let every programmer make up their own crap rather than to have an efficient, compiler supported standard for dispatch tables.

  71. Haiku uses C++ in kernel by Anonymous Coward · · Score: 2, Informative

    Haiku (formerly OpenBeOS) has had parts of the kernel in C++ since the beginning.

    Most notably the reimplementation of the Be File System. (Now OpenBFS)

    http://cvs.sourceforge.net/viewcvs.py/open-beos/ cu rrent/src/add-ons/kernel/file_systems/bfs/
    The filesystem is not slow at all. Actually the Haiku-people did some speed comparisons with Be's BFS and OpenBFS won.

    Other parts of the kernel is C++ as well. The device manager, an experimental vm..

    I've never really understood this anti-c++ in kernel thing.

  72. Most embedded development is still C based by Anonymous Coward · · Score: 0

    "Embedded dev is now often C++ based."

    Your comment is at best misleading, and at worst flat out wrong.

    I have no idea what type of embedded development you do, but I strongly
    suspect it's at the application level - not the kernel.

    In the Linux/UNIX/BSD area (which these days comprises most of the
    embedded development out there), embedded development is mostly C based,
    with C++ applications thrown in, maybe.

    If you do a count of the code size, including the standard Linux utilities,
    and libraries, you end up with most of the code still being C. I grant that
    you could come up with a bloated C++ application which out does this. But if
    you've got such a beast, it's usually due to code bloat.

  73. C++ is a bad idea for bad programmers by Chemisor · · Score: 4, Insightful

    > // C++, is this really better?
    > Register_set regset(base_address);
    > regset.write(SOMEREG_OFFSET , Register_set::BIT_A | Register_set::BIT_B);

    Only a complete novice would write code like this. Your code setting *SOMEREG_ptr = BIT_A | BIT_B will work just fine in C++ too. In fact, you could transparently support multiple types of registers by overloading operator= of SOMEREG_ptr, which could be a polymorphic class. And if you think that is going to bloat your code, you obviously have never looked at the output of a good compiler like gcc. A good C++ design is FAR more readable than any C hack you can come up with.

    > Typical compilers for DSP's lag the C++ standard by 10 years

    That is the problem of your compiler, not the language. Stop bashing C++ when you should be blaming your vendor for not being able to write a decent compiler, or even port gcc to their platform.

    1. Re:C++ is a bad idea for bad programmers by Anonymous Coward · · Score: 0

      That is the problem of your compiler, not the language. Stop bashing C++ when you should be blaming your vendor for not being able to write a decent compiler, or even port gcc to their platform.


      Not true. If a language sucks, is too complex to understand, or has poorly done (ambiguous) standards, it is the problem of the language. Personaly, I think C++ is in all three categories.
    2. Re:C++ is a bad idea for bad programmers by Anonymous Coward · · Score: 0

      If you think C++ is too complex to understand get the hell out of IT and give me your job.

    3. Re:C++ is a bad idea for bad programmers by akuma(x86) · · Score: 1

      So, instead of a simple "OR" instruction that the C code would compile to, you want to support a polymorphic class???

      This will compile to an indirect-branch (to figure out which class to use at run-time) --no matter what compiler you use -- and will most certainly slow your DSP application down, since the last time I checked...DSPs don't have indirect branch predictors. In fact, Prescott (latest P4) is the only Intel CPU with an indirect branch predictor.

      The reason why embedded and system developers like C, is that it's really close to the hardware -- which they are often trying to control in a very direct way. I think of it as a shorthand for assembly.

    4. Re:C++ is a bad idea for bad programmers by Foole · · Score: 3, Insightful

      I think you missed his point.

      The code sample was meant to show that some people will find excuses to use C++ features when the C equivalent works perfectly well. *HOPEFULLY* this won't happen in linux.

      amightywind wasn't bashing C++ in general, only in the context of embedded dev. I think they made this perfectly clear in the first 2 lines.

      I'd say they do blame the vendor, but the current state is that C++ in not good for embedded dev. If you can't get a good C++ compiler for the platform, then C++ is not a good choice of language. This has no direct reflection on C++ as a language.

      --
      This is not a turnip.
    5. Re:C++ is a bad idea for bad programmers by Anonymous Coward · · Score: 0

      So, we should just start using a language without any compilers, since there's no problems with that language?

    6. Re:C++ is a bad idea for bad programmers by Anonymous Coward · · Score: 0

      Most C++ monkeys couldn't handle it. It requires rational thought and actual results.

    7. Re:C++ is a bad idea for bad programmers by amightywind · · Score: 1

      In fact, you could transparently support multiple types of registers by overloading operator= of SOMEREG_ptr, which could be a polymorphic class.

      The point is that people like you delight in creating gadget interfaces, and avoid minimal, repetative, direct programming designs.

      That is the problem of your compiler, not the language.

      C++ has been in vogue for almost 15 years. In all of that time very few compilers have been able to keep up with the bloat of new features. It says a lot about C++ that it is so difficult to come up with a decent implementation. My point is valid.

      --
      an ill wind that blows no good
    8. Re:C++ is a bad idea for bad programmers by k8to · · Score: 1

      So, there's no problem with C++ so long as we assume all the tools and users are perfect.

      That's what you said, right?

      --
      -josh
    9. Re:C++ is a bad idea for bad programmers by Chemisor · · Score: 1

      > So, there's no problem with C++ so long as we
      > assume all the tools and users are perfect.
      > That's what you said, right?

      No language can force a programmer to write good code. If you are a bad programmer, you will write equally bad code in C++, C, Java, Python, Ruby, Eiffel, Perl, Prolog, Lisp, or BASIC. A language may prevent use of certain "dangerous" things, like memory allocation, but such hacks only convert the bugs from one type to another. In Java, for example, you never have invalid pointers, but you have memory leaks instead; you have bounds checking which cause an exception if you overrun your array, but to a user an exception creates an outcome identical to a crash. Good code requires good programmers. Period. So yes, that's what I said.

    10. Re:C++ is a bad idea for bad programmers by Anonymous Coward · · Score: 0

      a) If C++ code sucks, the problem isn't entirely in the programmer. If it takes 1 year to learn every feature of C (and a few more to master) and 4 years for C++ (and eternity to master), the C++ code is more likely to be of lesser quality than the C code.

      b) If C++ compiler sucks, the problem isn't entirely in the vendor. If it takes half a year to write a working okayish C compiler and five years to write a C++ compiler you can be pretty sure that one of them is going to be more incomplete than the other.

    11. Re:C++ is a bad idea for bad programmers by Carewolf · · Score: 1

      You have logical flaw. It can not take longer to learn C++ than to learn C, since C is good C++. And people shouldn't learn every feature of C++, some of them are evil (like exceptions).

    12. Re:C++ is a bad idea for bad programmers by Chemisor · · Score: 1

      > it takes 1 year to learn every feature of C

      Bullshit. I can explain every feature of C to you in a few hours. C++ is no harder. The problem is not learning the language, it is learning to work with the computer in the first place. What you need to learn is how to design programs; a skill that has very little to do with what language you use. Learn to extract the problem domain and to implement it in a minimal interface. Learn to make interfaces in such a way as to be used by writing as little code as possible. Learn to see similarities in cut-n-paste code and to abstract them into a more generic function. Learn to see similarities in function sets and combine them into a class. Learn to see similarities between classes and generalize them into templates. And then look at the assembly output and learn how to make all your syntactic sugar collapse into a few instructions in all the right places. That is what takes a long time to learn, and if you do not know these things, you will write lousy code, whether in C++, Java, or C.

      > If it takes half a year to write a working
      > okayish C compiler and five years to write a C++ compiler

      You obviously have never written a compiler. C++ features are not that difficult to implement. I have written simple compilers (no, not for C++) that supported inheritance, encapsulation, and templates, in a few weeks. Optimization of output code is hard. Parsing language features is not.

      > If C++ compiler sucks, the problem isn't entirely in the vendor.

      Of course it is in the vendor. They wrote it, so if it sucks (i.e. does not conform to the standard), then it is nobody's fault but theirs. The ANSI standard has been around since '89 or so, and if the vendor has not fixed the compiler, it is most likely because they are not willing to pay someone to do it.

    13. Re:C++ is a bad idea for bad programmers by Anonymous Coward · · Score: 0

      You obviously have never written a compiler. C++ features are not that difficult to implement. I have written simple compilers (no, not for C++) that supported inheritance, encapsulation, and templates, in a few weeks. Optimization of output code is hard. Parsing language features is not.

      Well of course not, not ever. Obviously. Even if I had they would compile only my own self-made toy languages whose semantics I can pick myself.

      So let's move to you instead. Have you ever read a standards document? How about comp.std.c(++)? Do you have any clue about the cans of worms there? Can you write an example of an array used as an lvalue?

      Of course it is in the vendor. They wrote it, so if it sucks (i.e. does not conform to the standard), then it is nobody's fault but theirs.

      Fair game. How much is BB(47), by the way? If you can't answer, it's your fault. It's not that I made an unreasonably hard question.
      g++ obviously sucks too. It's entirely reasonable to expect better from its makers. How can it be that it has taken years from such a big group of people to fix all the issues?

    14. Re:C++ is a bad idea for bad programmers by pthisis · · Score: 1
      It can not take longer to learn C++ than to learn C, since C is good C++

      1. Restricting yourself to the common subset of C and C++ and claiming that you therefore know C++ is pretty disingenuous. If you learned only how to write programs with printf and for loops, but didn't know conditionals or how to write functions, you couldn't truthfully claim you had learned C. If you haven't learned the preponderance of C++ features you can't truthfully claim you've learned C++.

      2. WRT to the comment "C is good C++", there are plenty of valid C programs that will not compile under C++. There are plenty of programs that will compile as C and C++ programs but will give different output depending on which language is used.

      (That's leaving out stupid examples like "int new = 1;")

      C is most decidedly NOT a subset of C++ even if you aren't talking about features like "restrict" that are in C99 and not in any C++ standard (AFAIK).

      Off the top of my head:
      /* include stdlib.h, I don't feel like quoting out the angle brackets*/
      int main(void)
      {
      int *a = malloc(sizeof(int));
      printf("sizeof('a'): %d\n", sizeof('a'));
      return 0;
      }
      Compiles in C and prints "sizeof('a'): 4" on most Intel machines.

      But it fails to compile in C++, and if it did (by inserting a cast whose only effect in C is to suppress potentially useful compiler warnings, and thus is considered BAD in C code) would print "sizeof('a'): 1" on most Intel machines.
      --
      rage, rage against the dying of the light
    15. Re:C++ is a bad idea for bad programmers by spongman · · Score: 1

      I can't think of any circumstances where knowing the size of a const literal is useful.

    16. Re:C++ is a bad idea for bad programmers by pthisis · · Score: 1

      That's just one example of many differences between C and C++ (and 'a' will be treated as a char literal everywhere in C++ and an int literal everywhere in C). The point is that even if you get your C sources to compile under a C++ compiler there's a good chance that some subtle difference is going to bite you. And, as I said, that's leaving aside all of the C99 features that aren't in C++ at all (though some are being discussed for adoption by future C++ standards).

      --
      rage, rage against the dying of the light
  74. Exceptional programming by Baldrson · · Score: 3, Interesting
    If you want to optimize exception handling then choose an exception-based execution model. Most people -- particularly Perl programmers -- are familiar with the short-circuit "or" and short-circuit "and" style of programming. "and" binds more tightly than "or" so that a sequence of "and" looks like a normal execution thread with no exceptions, whereas a sequence of "or" looks like a cascade of exception handlers (if all the prior expressions in the "or" sequence fail then you take the next one as an exception handler).

    When I say "thread" above I'm not just throwing around an ad hoc term -- you can use this to provide the basis for parallel execution in an OS or language.

    There is an entire school of thought built around this idea called logic programming and it is based on the most widely used foundation for mathematics -- the predicate calculus.

    I don't know why people spend so much time and energy optimizing things that are less powerful.

    As for object oriented programming, As I've said before:

    Almost all the Object Oriented stuff people layer on predicates are, at best, an ad hoc, and poor, means of optimizing execution speed.

    Let me explain.

    One of the principles of polymorphism is that the same method has the same abstract meaning regardless of the kind of object. A predicate considered as a method subsumes such polymorphism by simply trying the various possible implementations of the method and committing to only those that succeed. If more than one succeeds then so be it -- that's the whole idea of relations as opposed to functions.

    So, one reason you want all this OO stuff is the inheritance hierarchies keep you from going through all possible interpretations of a given method when the vast majority of them will fail for a given object.

    Another, related, problem is that inheritance provides defaults without requiring a lot of thinking on the part of the computer. What I mean by "thinking" here is the sort of thing that is done by statistical imputation of missing data via algorithms like expectation maximization (EM) [clusty.com] or multi-relational data mining via inductive logic programming .

    So, the other reason you want all this OO stuff is so you can avoid mining a background database to provide reasonable defaults for various aspects of the data.

    Some might be concerned that over-riding isn't absolute in such a system -- that you don't absolutely block, say, more generic methods when you have more specific ones present, and they're right. You don't block those methods -- you lower their priority by lowering the probability of those implementations via the statistical methods of imputation and/or induction. In a microthreading environment they most likely won't get any resources allocated to them before other higher priority implementations have succeeded. In a single threaded/depth-first environment they will be down the list of desired alternatives -- but they won't be discarded until something equivalent to a prolog cut operation kills them off.

    However, and this is the important point, the work that has been expended toward OO facilities has vastly outstripped the effort that which has been put toward more parsimonious ways of optimizing predicate systems.

    One of the better predicate calculus systems out there -- more promising due to its use of tabling to avoid infinite regress on head-recursive definitions and its optimization of queries using some fairly general theorems of predicate calculus -- is XSB . It has an interface to odbc and a direct interface to Oracle, but it would be better if it had something like a

    1. Re:Exceptional programming by Anonymous Coward · · Score: 0


      I was wondering why this seemed both on target in a *very* general way, but slightly off-base in that over-complex way I've seen in insane graduate students. Then I looked at your webpage -- where I found more of the same. Some of it marginally offensive, actually. Loosely formulated "hypotheses" with what seem like really very shallow tests (described in terms too complex to justify).

      I know this seems ad-homenem, but it really isn't (in a negative sense).

      I suggest you get out of your house. Take the time, not to just come up with hypotheses and rather shallow but complex sounding tests of such -- but to actually build something that works and performs a useful task... ...then come back to us. Because if anything, *thats* what the truly successful academic/researcher *gets* -- is that theoretical underpinnings will help plan the route and are valid. But the proof is in the pudding so to speak, and wishing something was so or whining about how it isn't so isn't going to make it happen. *You* have to do it.

    2. Re:Exceptional programming by Ars-Fartsica · · Score: 1
      Another, related, problem is that inheritance provides defaults without requiring a lot of thinking on the part of the computer. What I mean by "thinking" here is the sort of thing that is done by statistical imputation of missing data via algorithms like

      This is a non-sequiter. The only logic applied to the failure case is that which the programmer codes. While I found the links interesting, they have nothing to do with the problem you are explaining.

      You are also missing the core premise of systems coding - to be close to the hardware, which necessarily precludes prolog.

    3. Re: Exceptional programming by Baldrson · · Score: 1
      The only logic applied to the failure case is that which the programmer codes.

      Indeed, failure cases can be thought of as default behaviors. You might have multiple options for default behaviors -- and the question is what priority you give these defaults.

      You are also missing the core premise of systems coding - to be close to the hardware, which necessarily precludes prolog.

      Programming close to the hardware merely means you are modeling the hardware and that model, rather than being compiled into code, is physically realized by hardware. Model theory is exactly what you need and predicate calculus is the way most mathematics express models.

    4. Re:Exceptional programming by Sinner · · Score: 2, Insightful

      I actually was wondering if this was a troll while I was reading it... parts of it read like text generated by a Markov chains... syntactically correct but semantically nonsense. There used to be (still are?) crapflooders on IMDb whose reviews were very similar in comprehensibility to this.

      But then I realised it's Baldrson, and the penny dropped. Most trolls are indistinguishable from idiots, but Baldrson is a genius who's indistinguishable from a troll. I think he comes from a parallel universe where his beard is considered normal.

      Someone needs to get Baldrson and ESR alone in a room together. I'm intrigued to know whether they'd fight or make out. But what if the combined comedy facial hair reached critical mass? Is it worth the risk?

      --
      fish and pipes
    5. Re:Exceptional programming by Anonymous Coward · · Score: 0

      That reminded me of Paradigm Odesey on the ZDNet boards (where has he gone now?).

      You will make a lot more headway if you can make your point as a story - a beginning, middle and end, with progression through it that does not backtrack except to clarify or emphasise.

    6. Re:Exceptional programming by Mock · · Score: 1

      It's been quite a long time since I was last treated to such a condescending comment as this.
      I also give you kudos for being completely off-topic.

      As far as using predicate calculus in preference to an icky imperative or OO solution, I give you the CRC-32 algorithm.

      Yes, you can solve it mathematically, but if you use a table of pre-calculated solution pieces and cheat a bit by using the partial result as a lookup into said table, you gain a multifold decrease in calculation time.

      Only a fool would throw out a solution simply based on how elegant it is.

    7. Re: Exceptional programming by Ars-Fartsica · · Score: 0
      Programming close to the hardware merely means you are modeling the hardware and that model, rather than being compiled into code, is physically realized by hardware. Model theory is exactly what you need and predicate calculus is the way most mathematics express models.

      Uh, no, and I am starting to think you have no idea what you are talking about.

    8. Re:Exceptional programming by haluness · · Score: 1
      I visited the site you linked to and 'Wow!'.


      This guy is a pretty impressive troll. Does he really believe in all that crap or is it just to kill time?

    9. Re:Exceptional programming by Sinner · · Score: 1
      This guy is a pretty impressive troll. Does he really believe in all that crap or is it just to kill time?
      The best thing is, I don't even know which one you're referring to!
      --
      fish and pipes
    10. Re: Exceptional programming by sexylicious · · Score: 1

      Actually, set theory is what you need. Specifically, the theory of hypersets which is a non-well founded set theory (where a set can be a subset of itself).

      From wikipedia:
      The theory of hypersets has been applied in the logical modelling of non-terminating computational processes in computer science (process algebra and final semantics)...

  75. Re:"The fact is..." he's out of touch by mikefe · · Score: 2, Interesting

    The fact is that the Linux kernel is not just C, it also has parts where it uses assembler because they don't trust even the C compiler for that part of the code.

    The fact is that in the kernel much of the low level code cares about the exact physical layout of memory, and if it were mostly C++ you would need more parts in assembly which must be ported to each archatecture.

    Yes, C can be used in a higher level, but you are calling functions that deal with the low level from there is a very much OO way.

    Also, when you see people benchmarking how many cycles a processor actually takes to perform a snip of code and analyzing the assembly of the C program, I sincerely doubt that they would not be able to do the same for C++.

    --
    There: Something at a specific location.
    Their: Owned by someone.
    Please make sure your english compiles.
  76. Shapiro's take on this by Peaker · · Score: 3, Interesting

    Shapiro is the guy working on a research Operating System project (The EROS system).

    EROS was originally implemented in C++, but then
    it was reimplemented in C.

    1. Re:Shapiro's take on this by AArmadillo · · Score: 1

      That guy does not seem to know what he is talking about. Exception handling (along with other things like RTTI) is an entirely optional feature of the C++ language. If you don't want it, compile without it. He had absolutely no complaints about C++ after he turned off exception handling, except that the compiler switches were different for each compiler he used (as if that wasn't the case for C compilers as well).

    2. Re:Shapiro's take on this by Anonymous Coward · · Score: 0

      Being pedantic, exception handling and RTTI are not optional features of the C++ language. However, most (all?) compilers offer a switch to turn them off but that doesn't have to be the case.

  77. ... yet isn't Symbian written in C++? by Big+Jojo · · Score: 1

    That's an OS used in deeply embedded environments called "cell phones". There's a real-time version.

    Or is that all userspace code, not kernel code? Looked to me like both use C++.

  78. C++ isn't needed to do kernel OOP by Anonymous Coward · · Score: 0

    People pushing C++, Java or other OOP languages for kernel level development just don't understand kernel development. One simply does not need all the baggage that they bring.

    The most efficient solution is what the Linux kernel is already moving toward; and, I might add, what Solaris has incorporated for years. Namely, developing things in terms of objects, when it is useful. You CAN do OOP in C already, you just need to know what you are doing.

    The question is whether all the extra baggage that C++ brings to the table is useful. IMHO, as a long-time kernel developer, no, not at this time. However, some of the techniques used by the OOP people DO have benefits, and more kernel people should recognize this.

    From what I have seen going on with the latest kernel development, this is indeed recognized, and things are moving in that direction. In an efficient manner, I might add. And certainly in C.

    If the drawbacks and bloat of C++ outweighed its benefits, then I could see it being used. But I don't see this happening in the near future. It will always be more efficient to do things in C; and adopt OOP techniques will be adopted when it is desireable. That approach impresses as much more efficient, well balanced, and desireable for kernel development.

    1. Re:C++ isn't needed to do kernel OOP by PenGun · · Score: 0

      Mod this .... oh never mind.

    2. Re:C++ isn't needed to do kernel OOP by jedimark · · Score: 3, Interesting
      Sure you can - if you like doing all the dirty work yourself... (not that anythings wrong with dirty work :-)

      Although sometimes it is good to throw in a little abstraction. Being able to visualise some things on a different level really does help a programmer wrap their head around difficult issues that can't easily be solved going the hard yards..

      For example, learning forth as a kid did wonders for me being able to get a very solid grasp on recursion. True, it's not something you use everyday, but it's a different way to think, and some problems can only be solved (efficiently) that way.

      (My point is...) Having a few different programming models at your disposal is not such a bad thing. Yes, along with C++ comes a little bloat, but it also includes C in the bargain. It'd be nice having a little choice for those who want it.

      My language of choice these days is a hybrid of C and C++ (well, more lazy C++) - sure it means I have to link in an extra library, but I can break out with a different model when I see a real need for it.

      It is a little different at the kernel level, but their really isn't much stopping that extra bloat being included when a module is loaded.

  79. Sticking with C slows innovation by Anonymous Coward · · Score: 0

    ..Maybe not necessarily in the kernel area, since a kernel has pretty few tasks normally, but in general. This is why I strongly disagree with http://www.gnu.org/prep/standards/html_node/Source -Language.html. The whole point of open-source software is that developers around the world can contribute to to projects they deem important out of good-will in their spare time, or at least extend them in a useful way for their own personal use. If a project is written in C (or even C++), a would-be contributor has to learn somebody else's coding style and try to understand a large, monolithic piece of software before making any contribution. This is a huge turnoff for someone who has a job to work at to make a living (especially a job that involves programming) or to a student who has classes. Sure, there are people who work on OSS for their regular work or zealots who don't mind programming all day, but you're missing out on a whole lot of potential by advocating an antiquated, low-level tool in an area where rapid, error-free and extensible development is most important. Imagine most Linux apps were coded in .NET. *falls back at the the roar of millions of slashdotters bawling* Ok, imagine *you* had created .NET as the official recommended environment for Linux application development. Extending functionality for an application would then be almost trivial, provided the developer used proper OO design. Heck, you wouldn't even have to recompile, because of loading at runtime. You'd also have stronger guarantees about what the application is allowed to do (no memory leaks, you can even run untrusted code in a sandbox). And debugging would be much simpler with a VM environment and an exception stack trace than it is with "the app crashes 50% of the time when I finish downloading a new theme". Not to mention that you'd be able to use your own favorite language yet interact with any older code you need to deal with, or write plugins in yout language instead of having to learn everyone's variant of Scheme. If you want an example of this, check out Eclipse. It lets you easily create plugins that latch onto well-defined "extension points" in each subsystem or existing plugin. Thus people have integrated support for many other programming languages and all kinds of extra features for the Java tools. Installing a plugin only involves copying its directory or zip to eclipse/plugins (for that matter, installing Eclipse itself only involves unzipping it). The built in plugin development tools let you create a new instance of the workbench with your new plugin in 1 click, and you can then debug, etc because everything is just running in a separate JVM that Eclipse has full control over. IMO, lack of a consistent, easily extendable framework is one of the biggest weaknesses of open source (especially Linux) right now. If Microsoft makes writing a plugin that does something cool for its office app, web browser, development environment or whatever easier than you do, and all I really want is to get the program I use most often to do something I really need, I won't hesitate about writing it for the Microsoft program instead of yours. And with .NET and Longhorn, Microsoft is moving towards just that.

  80. The kernel is too bloated as it is... by jedimark · · Score: 3, Insightful
    Something tells me the kernel tree needs a major prune... it's damn well past rewrite time. 36Mb download now? Come on, this is getting rediculous!

    Ged rid of all these crappy drivers and related crap out of the kernel source tree, and just provide the basics. They should start a new sister project for maintaining drivers, and split them up too for goodness sake. Why should I have to diff the whole stinking tree, if i've made a few changes to a networking components? or added a soundcard driver?

    BEOS was onto a good thing using the microkernel, completely seperate subsections for drivers, and the ability to control teams of processes - these would all be very useful in a mainstream O/S.

    C++ output may be a bit larger, but isn't all that bad, objects are very easy to visualise, and the source usually ends up smaller. Kernel Modules with a better designed interface would be an good start. And if C++ could help out here, why not?

    It's about time the kernel guys opened up to a some fresh ideas. Sure, linux is already an awesome O/S, but you can't fight an the evil dragon wearing nothing but asbestos undies...

    As long as they keep STL out of the kernel I will be happy. (imho templates make code look butt ugly and a behemoth to maintain)

    1. Re:The kernel is too bloated as it is... by PenGun · · Score: 0

      It's a good old *nix macro kernel pooky. The drivers you need are compiled, for the most part, right into the kernel. Sooo you gonna need _all_ the drivers for _all_ the hardware linux supports.

      There are ways around this and they will prolly start to seperate some stuff by arcitechture but till then 36m is what it takes.
      Those that live on the bleeding edge just keep patching what they got and those are 1 - 3 meg usually.

      PenGun
      Do What Now ??? ... Standards and Practices !

    2. Re:The kernel is too bloated as it is... by jedimark · · Score: 1
      Yeah, but if it can be built as a module, it dont really need to be in the mainline...:-/
      You need kernels source to build such modules, but not the other way around..

      I agree the platform dependant stuff is a mess, but if they split it, it could cause a few rifts in the kernel..? Last thing we need is 1024 seperate branches...

      Patches are fine if you run a stock kernel... (me speaking as a lazy gentoo-dev-sources user :)

      If anything split out of it, I do believe it should be available through the same distribution channel though as the mainline kernel, just _optional_.

  81. Re:"The fact is..." he's out of touch by ComputerSlicer23 · · Score: 1
    Well yes and no. C++ compilers have been broken for a long, long time. They are getting much better. I know I've run across things in C++ as recently as 2.96 compilers that are completely standards conformant, and won't compile with g++ 2.96. I'll used to develop on a 2.96 compiler and release with a 2.91 compiler. Let me tell you, that's a beast. I know I'm older versions there, but it was true circa 2001-2002 that 2.96 was the latest stable compiler released with most production quality Linux distributions.

    Now, I'm a C++ fan. I'm a huge C++ fan. It's my language of choice. However, Linus is correct, "C++ is just C anyways". Go take a good long hard look at cfront (not sure if that's still current). C++ was literally convertable to C. Still is to this day to the best of my knowledge. There is absolutely no construct in C++ you can make that I can't do in C. It might not be a simple, it might not be as easy, but it can be done. Virtual tables, are nothing but fancy tables of function pointers. Templates are nothing but a simplification for writting the same code over and over. References are hidden pointers that can't be NULL (unless you trick the compiler). Exceptions, ahh, now that's harder, but even their it's nothing but a setjmp, longjmp type problem. I'm not saying they are nearly as easy or useful to write, but it is in fact true. Even constructors and destructors are nothing but code that must run. If you are careful, you can arrange for that in C. Yes it's harder, but it's not impossible.

    Name a construct that has a useful application in the kernel that is in C++ that can't be easily duplicate in C with the use of arrays of function pointers and macros?

    Remember useful. Anytime Linus wants to hide the implementation details, he does, he just uses an opaque type. He doesn't have to worry about references or non-references (especially not the NULL pointer checks that happen on every access of a reference with g++ 2.96 (not sure about later versions), that you have to disable to speed up the code). There are lots of hidden things going on in C++. They are grand and glorious most of the time.

    The most useful constructs of C++ is the STL IMHO, and those are completely not allowed in a kernel. Too many memory allocations that happen transparently. Too many nasty bits where you can't access them in some specific context (interrupt context jumps to mind). You'd have to rewrite them yourself, and they already have an implementation of lists in the kernel that are C style templates.

    C++ is syntactical sugar that makes it easier to enforce certain things. That's it. It's a better C. However, the number of people who can do it, and do it well are few and far between. A good tool (like the one Linus has been working on), that checks to see if you are following a specific set of rules, would be much more useful then attempting to graft C++ into the existing kernel. We'd be much better off to write tools that ensure you are using the API they way you are supposed to, rather then attempting to write the API so that C++ can check it. C++ has no concept of "interrupt context", it has no concept of "preemptible code", it has no concept of per-CPU data structures. Those are the things that need to be checked in a kernel. Not if you are accidently accessing a data memeber you shouldn't be.

    A lot of the things that have been added to C++ aren't going to make it better for writting an OS then C is. You can write some wonderful interfaces useing just straight C. It's more complex the most part. If nothing else, I wish that the Linux kernel would use C++ just to get namespaces, but that's just me. C++ does have times when it can take templated code and optimize it better then C can due to it's more advance understanding of type , const'ness and inlineness. However, remember that kernel hackers would just write a custom version and use it when it's a measured speed problem.

    Kirby

  82. What about BeOS? by JohnDeHope3 · · Score: 3, Insightful

    I thought the BeOS was written all in C++ and it was darn fast. Or perhaps just the public API was C++ and the actual stuff underneath was C? I dunno. I liked the BeOS. Hmm that RC5 cd is around here someplace...

    1. Re:What about BeOS? by Anonymous Coward · · Score: 2, Informative

      Be had a strict "no c++ in the kernel" rule. You're correct in that they did use c++ extensively in user space.

  83. Approach -- and meet by devphil · · Score: 2, Interesting


    Even g++ can give the zero-overhead ideal for exceptions. It's heavily dependant on the platform and the platform-specific ABI.

    Linux on x86 ain't one of those platforms.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
    1. Re:Approach -- and meet by Foresto · · Score: 1
      "Even g++ can give the zero-overhead ideal for exceptions. It's heavily dependant on the platform and the platform-specific ABI. Linux on x86 ain't one of those platforms."
      References, please?
    2. Re:Approach -- and meet by devphil · · Score: 1


      One of the messages by a maintainer on the gcc-patches list in the last month, maybe month and a half. I wish I'd kept a link to it, but I didn't. The archives are at gcc.gnu.org/lists.html if you want to search.

      --
      You cannot apply a technological solution to a sociological problem. (Edwards' Law)
    3. Re:Approach -- and meet by IamTheRealMike · · Score: 1

      I'm 99% certain gcc/linux/x86 uses a zero overhead table-based exception ABI. Try dumping a C++ binary some time and check out the .eh_header section.

  84. Nice troll. by devphil · · Score: 1


    as recently as 2.96 compilers

    Which are now 4 years old. They're dead. They're unsupported unless you pay hefty dollars. They're known to be non-complaint with any C++ standard, ever. They never were.

    C++ is syntactical sugar

    So is C. So is anything above assembly. Door's that way, troll.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
    1. Re:Nice troll. by ComputerSlicer23 · · Score: 1
      Well, take me up on my challenge:

      Name one feature of C++ that is compelling and useful for the kernel that can't be accomplished in C in a maintainable fashion?

      It's a simple question, one I posed before. Are you going to answer it or call me a troll for pointing that until the last 2 years, there wasn't a decent C++ compiler. The 2.4 kernel series still lits in it's documentation, that egcs-1.1.2 (which I believe corresponds to gcc-2.91), is still being supported. So it's not a completely irrelavent point.

      http://linux.bkbits.net:8080/linux-2.5/hist/Docume ntation/Changes?nav=index.html%7Csrc/%7Csrc/Docume ntation

      Look for the entry that says "Enforce gcc 2.95 compiler as the minimum". Hey, look at that, right next to it that says, 19 months ago that was the minimum. So as off 19 months ago, it sorta follows that they had to support the what you seem to reguard as a substandard C++ compiler. I believe that 2.91 is still used as the compiler of choice for older Sparcs. That's during the 2.5 development kernel.

      http://linux.bkbits.net:8080/linux-2.5/anno/Docume ntation/Changes@1.33?nav=index.html%7Csrc/%7Csrc/D ocumentation%7Chist/Documentation/Changes%7Cdiffs/ Documentation/Changes@1.33

      Hey, look at that, in the 2.6.0 Documentation/Changes, the required version is still 2.95.X (x>=3). So which version of the C++ compiler did you want to you?

      So while you might think they are 4 years old, and unsupported, it is still the version that Linus says is the correct version of the compiler to use. You might think I'm a troll, but at least I know the details of the projects I use. *sigh*, I wish people paid attention to details once in a while. The kernel is very sensitive to the version of GCC it is compiled with. As a general rule that means they are very reluctant to require newer versions, or even support newer versions.

      Actually, assembly is syntactical sugar, do in in machine code (or if your into Turing machine, with punched paper tape). It's nice of you to call me a troll, but you still have yet to state a compelling reason why C++ is a good idea to have in the Linux kernel. C++ and Objective C (I've programmed in both professionally), are very slick ways of accomplishing things that can be done in straight up C (especially Objective C). C++ is much nicer to program in then C if only because it means I never have to null terminate a string again. Given a choice, I'd never ever write a line of C again in my life.

      The subset of C++ that is actually hard to do a good job of in C is nearly identically the subset that wouldn't be useable in the Linux kernel. Most of the best ideas for using C++ in the kernel are type checking and virtual functions. Type checking is already a problem (Linus points out that GCC emits spurious warnings about code that is obviously correct to anyone who takes a cursory look at the code w/ the 3.X series of GCC, it would only get worse with G++). He's writting his own set of tools to do type-checking that is tailor made for the Linux kernel.

      http://www.kerneltraffic.org/kernel-traffic/kt2004 1019_278.html#5

      Virtual functions are nothing but a table of function pointers. They do this all the time in the Linux kernel. I'm asking a simple question, name something besides those two features of C++ that are a tool that needs to be used in the Linux kernel that would be impossible to maintainably implement in C.

      I wish they had namespaces, but that's not something that is impossible to do in

    2. Re:Nice troll. by devphil · · Score: 1

      I'm not even reading all of that. Your argument falls down as soon as you point to "documentation: that is hopelessly outdated and known to be abondoned and unmaintained.

      --
      You cannot apply a technological solution to a sociological problem. (Edwards' Law)
    3. Re:Nice troll. by ComputerSlicer23 · · Score: 1
      You are an odd fellow. I ask a simple direct question three times and you still duck it. You seem to have a habit of posting information like it is common knowledge and then fail to back it up with some type of reference or source material.

      Never mind all that. You seem to be intelligent, and relatively active in this thread about C++ and it's good points. So I'd really like your opinion on one single question. Completely disreguard the other issues.

      Name one compelling feature in C++ that you feel is unmaintainble in C, that would make a significant impact on the Linux Kernel and the quality of the source.

      You can't use virtual functions or type checking. GCC and G++ already annoy Linus with the type checking, and the Linux kernel is a fine example of how to implement virtual functions in C. You can't take namespaces either, as while they are nice, I believe they are not "unmaintainable" without them in C.

      Kirby

    4. Re:Nice troll. by devphil · · Score: 1


      "You can't use virtual functions or type checking. GCC and G++ already annoy Linus with the type checking"

      Well, that's one of the many places where I disagree with Linus. One of the whole points of C++ was to tighten up the type system. That alone would be worth it, in my opinion. If it "annoys" him, too bad for him.

      --
      You cannot apply a technological solution to a sociological problem. (Edwards' Law)
    5. Re:Nice troll. by ComputerSlicer23 · · Score: 1
      If that's all you really want it for, there are a number of good tools to statically type check. Linus is working on one that is tailor made for the Linux kernel. g++ doesn't accumulate all of the information it should to realize that there is nothing wrong during a lot of warnings it prints out. Even gcc 3.4 goes overboard with it's type comparisons.

      Lint, split, and the python scripts (one of the kernel janitors does this), smatch I believe is the name that process the output of the GCC RTL all do a good job, why not work on extending them. There's nothing compelling about doing the type checking in C++ it's trivial to do it in C, one can easily do that in C with external tools, or by modifing GCC specifically. Type checkers have been doing it since before C++ was even the name of C++.

      Man getting you to state anything is like pulling teeth. Any chance you'll just list more then one "of the many places where I disagree with Linus"?

      Type checking is the obvious one, virtual functions the other.

      Kirby

  85. Question by cybersavior · · Score: 1

    This seems to be turing into an all out war! Im a CS student in college and we're learning Java now, but in my CS class in High School, it was C++. I never became advanced enough to really compair C++ to anything, espically C. Could someone recomend a book or online article that fairly debates C vs C++, perhaps in terms a n00b level programmer could understand?

    1. Re:Question by multipartmixed · · Score: 2, Interesting

      Different strokes for different folks.

      You're a CS student in college, you don't really need to know. What you need to spend all your time doing is learning how to PROGRAM and do it well.

      Worry about the specific tools later. You could do just as well with just about any language of the right paradigm. C++ is actually a mixed-paradigm language, not all that great for teaching.

      --

      Do daemons dream of electric sleep()?
  86. troll? how so? by bani · · Score: 1

    /, moderators continue to amaze.

    1. Re:troll? how so? by Anonymous Coward · · Score: 0

      he spells the name "Linus" as "Linux"...

    2. Re:troll? how so? by Anonymous Coward · · Score: 0

      That doesn't make him a Troll, that just means he is an idiot who doesn't proof-read.

  87. Re:"The fact is..." he's out of touch by Anonymous Coward · · Score: 0

    You missed the word "particular", Einstein. Meditate on it.

  88. What about a, I don't know, by Anonymous Coward · · Score: 0

    GOOD LANGUAGE? C++ is just a pile of crap bootstrapped on to C. Obj-C, Smalltalk, Perl/Ruby (With perlcc. I hope that we might get a rubycc soon) or maybe even JAVA (compiled into binary, not bytecode) would be good. Now, I don't like Java's syntax that much, but its better than CCrapCrap.
    To support Obj-C all they'd have to do is include the Obj-C runtime. No problem.

  89. Yeah, it's not, until someone finds out by melted · · Score: 1

    that what you thought was exception safe is in fact not exception safe. I've seen our local C++ "god" spend entire week hunting down a signle bug which only manifested itself after a few days of intensive load test. The code was multithreaded and it had to be thread safe as well. Turns out, even the guy who has been using C++ for 10+ years now could not write multithreaded exception safe code. He could not find the bug by just looking at the code, either. He ended up working on a memory dump and calling in other experts from around the company to figure out what was going on. They spent five days to find out that exceptions didn't quite work the way they expected them to and because of this there was an extra decrement on a variable in RW lock which deadlocked the waiting threads.

    1. Re:Yeah, it's not, until someone finds out by Anonymous Coward · · Score: 1, Insightful

      You need to understand that multithreaded execution is outside the scope of the ISO C++ specification, just as it is with ISO C. Thread safe exception handling requires extra runtime support; 'spinlock' is not a keyword in C.

  90. Mozilla, pah by Anonymous Coward · · Score: 0

    Sod that. I want UT2004 in the kernel.

    It's all about the framerate, baby.

  91. mod parent up! by bani · · Score: 1

    perfect example of why c++ doesnt belong in a kernel. with proof by someone who wrote a kernel in c++.

    1. Re:mod parent up! by Anonymous Coward · · Score: 0

      Shapiro is an idiot, though. His writing reads like something that doesn't understand C++ but insists he does because he's been not understanding it for a long time.

  92. Polymorphism demands heap allocation by Chuck+Messenger · · Score: 1

    Ok, so don't use the heap. There is no reason that C++ needs to use the heap; everything can be allocated on the stack. Just like C.


    Well, not _entirely_ true. I mean, obviously, you can program C++ without doing mallocs. The question is, if you restrict yourself in that way, do you give up a major feature of the language? The answer is Yes -- you lose polymorphism, in effect. In order to use objects polymorphically, you must pass pointers to them. The pointers can be upcast/downcast. If you don't pass a pointer, then your object is stripped.

    Admittedly, it is possible to pass around pointers to stack-based objects. But in my experience, you don't end up with safe code. What you want is reference-counted objects. Such objects must be allocated on a heap.

    I only bring this up because, over the course of several years' C++ programming, I've gradually eliminated almost all heap-based (well, explicitly heap-based) activity. I can do _almost_ everything with stack objects and STL containers. However, whenever I need to make use of polymorphism, I find that I need a reference-counted heap object.
    1. Re:Polymorphism demands heap allocation by swillden · · Score: 1

      However, whenever I need to make use of polymorphism, I find that I need a reference-counted heap object.

      And how often do you need to polymorphism on short-lived objects?

      Long-lived objects, even in kernel code, are allocated on the heap, and those are also the ones that benefit from polymorphism. The Linux kernel makes heavy use of polymorphism, actually. And reference counting. And all of those objects are heap-allocated.

      Really, the issues here are absolutely no different between C and C++.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    2. Re:Polymorphism demands heap allocation by Col+Bat+Guano · · Score: 1
      A different language, for sure, but Ada allows polymorphism without heap allocation.

      Just another data point...

    3. Re:Polymorphism demands heap allocation by Foolhardy · · Score: 1
      The question is, if you restrict yourself in that way, do you give up a major feature of the language? The answer is Yes -- you lose polymorphism, in effect. In order to use objects polymorphically, you must pass pointers to them. The pointers can be upcast/downcast. If you don't pass a pointer, then your object is stripped.
      This is a good question; how many features should be actually used? C++ has many and it is possible to choose only certain ones. Maybe polymorphism would have to be avoided.
      Admittedly, it is possible to pass around pointers to stack-based objects. But in my experience, you don't end up with safe code. What you want is reference-counted objects. Such objects must be allocated on a heap.
      Hmmm, I haven't had problems with stack pointers, but I hardly use them either. Ref-counted (or tracked) objects ARE easier because you can store them. I don't use much heap allocation, but I also don't use many virtual functions or much inheritance.
    4. Re:Polymorphism demands heap allocation by Anonymous Coward · · Score: 0

      You can use "placement new" and "placement delete" to place objects in pre-allocated/staticly-allocated memory.

      This way will not use the heap, but still have the benetits polimophism privides.

    5. Re:Polymorphism demands heap allocation by Chuck+Messenger · · Score: 1

      True -- in effect, you're implementing your own heap, which is (hopefully) more suitable than the default heap for your application. But if you start really using it -- lots of allocations/freeing, many different object sizes, multiple threads -- then you'll probably find that the default allocator has better performance than your custom one (unless your custom allocator is quite sophisticated).

  93. GOTO instead of nested conditionals by Anonymous Coward · · Score: 0
    Using nested conditionals is stupid.. Instead use goto:
    if(failed(doSomething())) {
    goto CLEANUP1;
    }

    if (failed(anotherThing())) {
    goto CLEANUP2;
    }

    CLEANUP1:
    cleanUp1();
    CLEANUP2:
    cleanUp2();
    return;
    this is much cleaner than ugly nested conditionals.. and it is the reason goto was kept even for languages like Pascal!

    I don't care what you think about structured programming.. this is the ONE good use for gotos.
  94. Re:"The fact is..." he's out of touch by Anonymous Coward · · Score: 0

    There is absolutely no construct in C++ you can make that I can't do in C. It might not be a simple, it might not be as easy, but it can be done.

    That's because both languages are Turing-complete, idiot. You can convert any construct in Scheme or Prolog or Brainf*ck to C, as well.

  95. C++ compilers are untrustworthy by bill_mcgonigle · · Score: 1

    Anyone who claims with a straight face in 2004 that "C++ compilers are untrustworthy" is trolling. Sorry, rabid penguin lovers.

    The fink project has recently traced crashing problems to gcc 3.3 generating incorrect output from C++ code.

    As of about mid-2004.

    --
    My God, it's Full of Source!
    OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
    1. Re:C++ compilers are untrustworthy by Quantum+Jim · · Score: 1

      Do you have a reference? I'm not taking anything away from you... I'd just like to see the relevent bug reports.

      --
      It is impossible to enjoy idling thoroughly unless one has plenty of work to do.
      - Jerome Klapka Jerome
    2. Re:C++ compilers are untrustworthy by scotch · · Score: 1

      There were some optimization bugs in the gcc 3.1 series - documented in gcc bug database I'm sure. These bugs applied both to C and C++ mode. If the grandparent post is implying that C++ compilers have bugs whereas C compilers do not, he'd be wrong, of course.

      --
      XML causes global warming.
    3. Re:C++ compilers are untrustworthy by bill_mcgonigle · · Score: 1

      Do you have a reference? I'm not taking anything away from you... I'd just like to see the relevent bug reports.

      I think you'd have to wade through the fink-devel lists to find 'em - if you just want a mention, follow the link I included; it's on their front page.

      --
      My God, it's Full of Source!
      OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
    4. Re:C++ compilers are untrustworthy by Quantum+Jim · · Score: 1

      Thank you! I should have seen that.

      --
      It is impossible to enjoy idling thoroughly unless one has plenty of work to do.
      - Jerome Klapka Jerome
  96. C's reason for existence; BSD versus Linux by bcrowell · · Score: 2, Insightful
    A few random thoughts about this:
    1. Choosing a programming language is all about choosing the right tool for the job. To me, the last couple of decades' worth of buffer overflow exploits show that C is not the right tool for writing application programs. Still, there was always at least one big justification for the continued existence of C: low-level OS programming. If there were really signs of migration away from using C for that job, then I'd really start wondering whether C was anything more than a legacy language.
    2. I would've actually gone the other direction: C is too big and complicated for OS programming, and includes too many unnecessary features. For example, it's perfectly possible to write an OS without ever using floating point.
    3. C++ would be a badly designed language if you considered it only in its own right. The only reason it had to be complicated and crufty is that it was designed for backward compatibility with C. But if C is becoming irrelevant, then why should we saddle ourselves with a bag-on-the-side like C++ for the sake of C compatibility?
    4. I assume Linus will reject the patch, but if the Linux kernel ever did become C++-based, this would be an interesting new differentiation between Linux and BSD. BSD already has the edge in server performance, and I assume that a switch from C to C++ would incur at least somewhat of a performance hit.
    5. Does anyone know if C++ is in use in other kernels, such as Hurd, Mach, or Plan 9?
    1. Re:C's reason for existence; BSD versus Linux by Anonymous Coward · · Score: 0

      BSD already has the edge in server performance...

      On what basis do you say this? I'm genuinely interested, not just yanking your chain.

      Can you link to any credible, recent (FreeBSD 5.x vs. Linux 2.6.x) benchmarks that support your assertion?

    2. Re:C's reason for existence; BSD versus Linux by downbad · · Score: 2, Informative

      according to these benchmarks, linux 2.6 is faster freebsd 5.1.

    3. Re:C's reason for existence; BSD versus Linux by bcrowell · · Score: 1

      FreeBSD 5.1 is a development version, not a production release. The 5.x development versions are slower than the 4.x production releases, but this should be fixed by the time the final version of 5.3 comes out.

  97. Yuk, no! by Anonymous Coward · · Score: 0

    I'm tainted - in the days of punched cards, // in the first two columns signified a job control (JCL) statement to IBM mainframes, and you NEVER wanted to write a program that relied on those characters in those columns EVER. Just seeing it adopted in C++ (and gcc) gives me the willies. The only worse combination was /* (oops, isn't that a comment in C?).

    While Linux started out as x86 only (and is obviously mostly used there), it actually runs on lots of architectures, which I think is a GOOD thing if you can manage it, and which defeats the argument that it should be written in assembler.

  98. i dont care... by Anonymous Coward · · Score: 0

    Why dont they just make it all in assembly? Would be alot faster...ohhyeah.

  99. Re:"The fact is..." he's out of touch by Anonymous Coward · · Score: 0

    Current Operating System kernels created by Linus: 1
    Current Operating System kernels created by devphil: 0

    priceless...

  100. Re:"The fact is..." he's out of touch by Hard_Code · · Score: 1

    Depends on whether you consider kernel modules "in the kernel". It allows kernel modules to be written in C++ (they give 2 sample modules) which before apparently was required lots of extra redundant support code. Nobody is forcing kernel (proper) developers to use C++.

    --

    It's 10 PM. Do you know if you're un-American?
  101. MOD PARENT DOWN by r6144 · · Score: 1
    I have RTFA. It does exactly add C++ support to the kernel (including modules).

    Neither the kernel proper nor kernel modules are commonly called "userspace".

  102. (Now if only I could spell) by IBitOBear · · Score: 1

    Yes, on re-read I even have errors in the title. Sigh. I furvently wish this site had the nice "check spelling" button like on the bottom of the gmail compose page.

    I just cannot seem to keep my dyslexia from misfireing all over anythin I type when I am this pressed for time.

    (Slashdot is not work-hours compatable unless I am really fast... 8-)

    --
    Innocent people shouldn't be forced to pay for inferior software development.
    --"Code Complete" Microsoft Press
  103. I can't wait... by funklord9 · · Score: 1

    until the kernel supports java.

  104. Re: exceptions vs return values by Anonymous Coward · · Score: 2, Interesting
    The parent poster has the right idea when he said "if you ever throw exceptions exclusively at one level and catch them exclusively at the next level up, there's a good chance you're using the wrong tool for the wrong job."

    In theory, an exception is just a more expedient return statement -- it lets you immediately branch to the handler. In some sense, they're a bit like using setjmp/longjmp, labeled branches (a feature not found in C/C++), or continuations (another feature not found in C/C++). But it also means that there is absolutely no benefit provided if you only use it as an alternate means of returning to the caller.

    Exception handler addresses can be pushed onto the processor stack just like the return instruction pointer (or they can be pushed onto a separate exception stack). Any function that needs to do exception 'cleanup work' can push its own exception address instead of its caller's.
    a() catches
    b() ^
    c() |
    d() |
    e() throws
    If you're passing an exception through multiple functions, raising an exception can bypass significant number of comparisons and jumps. It also reduces clutter in the intermediate functions that don't have to bother testing for an error condition and passing back a return value.

    However, in C++ you run into the situation where 1) nearly EVERY function has an implicit exception handler to calls all the destructors for the stack variables, and 2) optional exception handlers require expensive runtime typechecking comparisons to see which handler gets to run. The former means you don't end up saving much with C++ catch-all exceptions (i.e. "(...)"), and the latter means you actually end up losing performance with type-specific exception handlers! The article mentions using pointer comparisons here to help reduce this performance hit.

    Basically you use C++ exceptions for convenience/safety, not performance. They're particularly useful when you're calling 'unknown' code like virtual functions/function pointers (in other words: drivers), and that's why there's interest in using them in the kernel.
  105. kinda useless... by Ayanami+Rei · · Score: 3, Interesting

    Having a linux kernel running as a layer on top of a JVM is kinda useless since it's designed to run some sort of native binaries. So the question becomes: which target architecture do you then emulate in the JVM to accomodate the user space programs, or do you force all userland apps to be java bytecode as well? Then what's the point? Just use straight java on the JVM.

    Really, more useful would be a full-fledged java-based x86 or whatever simulator with emulated hardware that a kernel would target. Then any standard propietary binaries could run in that, and even be migrated across an java cluster.

    --
    THIS THING CAN TURN ON A DIME, MACROSSZERO STYLE ALSO FUCK BETA, ~NYORON
    1. Re:kinda useless... by Anonymous Coward · · Score: 1, Interesting

      Better yet, the kernel is the VM; which is the hardware abstraction layer, micro JIT loader, and the virtulization logic for all system processes, with the common java api's layerd on top. That way the 'operating system' proper would be extensible and the Java language self hosting after the first generation due to the native boot level JIT translator. The bootstrap coding and HAL needs to be a JIT binary cache of the first run but the rest of the OS could be assembled on the fly. Truely write once run anywhere once the OS abstraction objects are cached during the first run through the interpreter. Classes could be loaded like drivers to extend the OS or user environment as needed.

    2. Re:kinda useless... by kjots · · Score: 1

      Yes, all user apps would be in bytecode. Java bytecode would be the native binary format of the platform, in the same way that x86 machine language is the native format on PCs. The point is to have a completley self-contained Linux environment running inside a Java virtual machine. Obviously, you would need to port the compiler and other components of the toolchain, user space apps, etc. JVM would become an architecture, like i386, ppc, ia64 and anything else under the '/usr/src/linux/arch' directory.

      It would be useful only as an excercise 'to prove it can be done'; I doubt it would serve any practical purpose. But as I implied earlier, simply to prove something can be done is often a good enough reason in itself for us geeks. If nothing else, we would learn a hell of a lot about Java and bytecode in general.

    3. Re:kinda useless... by sjames · · Score: 1

      which target architecture do you then emulate in the JVM to accomodate the user space programs, or do you force all userland apps to be java bytecode as well?

      It MIGHT be interesting to see User Mode Linux running in JVM. It would require setting up a new arch for the userspace. It would be a great deal of work.

      Of course Interesting is one thing, worth it is another. Perhaps if someone is hard up for a research paper?

  106. wait a minute.. by tasinet · · Score: 2, Funny

    ..you mean the linux kernel isn't written in Visual Basic?

  107. Gee what "advice"... by Baldrson · · Score: 1
    Now how about "getting back to us" with your identity so we can see how credible your "postive" ad hominem is. Comparing resumes and all that so we can call each other "positive" things like "insane" and give each other "advice" like "get out of the house more often". And, no, I'm not asking for yet another anonymous response -- this time of your supposed "resume" san identity. You set the ground rules for considering the source of an argumet so follow them.

    As far as my priorities on implementing an OS based on the predicate calculus criteria I set forth -- I'll "get back to you" after I've handled a lot of very much more important issues. I'm 50 years of age with a lot of responsibilities. If I give advice and refuse to take it from some anonymous coward who thinks he's qualified to diagnose sanity and judge the merit of scientific arguments that are too threatening to his world view to consider them without reacting against their source, then so be it.

    If I do happen to break free of more pressing matters and can afford the time to spend doing this sort of system, you should not, in your anonymous narcisism, convince yourself that your "advice" contributed to the completion.

    1. Re:Gee what "advice"... by Anonymous Coward · · Score: 0

      Then perhaps you might take this advice from another anonymous coward. Seek trained pstchiatric help my friend.

      Also. I would be willing to bet my right arm that you will never break free of more pressing matters because it is the imagined blockage that they create that allow you to keep on deluding yourself.

      Also. _Delete_ your website. It is only interesting for purely anthropological reasons. Be brave, admit it, your ideas don't gel with reality in general.

  108. Re:"The fact is..." he's out of touch by RedWizzard · · Score: 1

    The kernel developers have found a number of bugs in GCC over the years. Do you think it's unreasonable to say that G++ is likely to be more buggy than GCC?

  109. Re:"The fact is..." he's out of touch by torokun · · Score: 1

    Not true. (the bit about untrustworthiness of cpp compilers)

    C++ has quite a few areas of the language that actually exhibit _undefined_behavior_. Sure, on any one implementation it may be predictable, but there are still quite a few things that you could ask Stroustrup about and he'd say "well, just stay away from that, eh..."

  110. Re:"The fact is..." he's out of touch by alder · · Score: 2, Informative
    It doesn't add C++ support to the kernel...
    That's not what the articel says ;-) - "We have implemented a complete kernel level run-time support for C++ in the Linux kernel." And a bit farther: "The implementation of the C++ ABI is based on the implementation provided with the source of the GNU g++ compiler. We modified it to run in kernel space..."
  111. Fast kernel, slow hdd rates by evil9000 · · Score: 0, Offtopic

    Have they fixed SATA support in 2.6.x so that i can use DMA on my drives yet? Thats the only reason i'm using 2.4 vs 2.6. 150megs per sec vs 10megs per sec. Makes a big difference...

  112. Advantages of C++ by Spy+der+Mann · · Score: 2, Informative

    If the Kernel is C++, this means the API calls can ALSO be C++ (with some restrictions, of course). This could mean no more kernel-recompiling for loading modules, no more .so recompiling and ending the .os dependancy hell...

    What we're talking about is using a whole new computing paradigm in the very core of an operating system. (it may be not new for apps, but for the kernel... just think about it).

    As an OOP'er, I'm frankly excited by the idea.

    And no, we're not talking about interpreted runtime languages like C# or java. We're talking about the REAL thing.

    C++ means that the code will be easier to maintain, changes will be easier to track, and who knows. Perhaps a boost in the development that might JUST be what Linux needs to defeat Winblows as the next Desktop OS.

    1. Re:Advantages of C++ by Taladar · · Score: 1

      You have much to learn if you blindly tell about the advantages of one paradigm and dismiss the disadvantages. Every paradigm (imperative, functional, OOP,...) has both of them.

      Personally I do not think OOP would make maintaining of Kernel Code easier since in the Kernel you have a real advantage from being able to image the Assembler-Code/Hardware-Operations involved. OOP is simply to far from actual Hardware to be used for this lowest level Programming.

    2. Re:Advantages of C++ by grmoc · · Score: 1

      Strong disagreement.

      C++, with its explicit variable scoping, is very good at dealing with exceptions and the consequences of cleaning up resources when they occur.

      In a non OO language (and even other OO languages, such as Java, etc), you have to manually remember to unlock a resource (such as a mutex), whereas in C++, the destructor (Guard pattern) takes care of that for you. This is a direct consequence of being OO (with scoped variable lifetime).

      C++ has very nearly all of the hardware accessing capabilities of C. (The only thing I know about that is 'lesser' is that you have to cast a float or a double to another type in order to perform bit manipulations. This is trivial.)

      Furthermore, the assertion that OOP is too high level to describe hardware seems flawed.

      Why is it 'too far from the actual Hardware'?
      What is it that you can model in a language such as 'C' that you cannot model in 'c++'?

      Inline assembly is not a problem, various constructs for doing just that are available.

      C++ is a mixed paradigm language. In fact, it does a horrible job of enforcing any paradigm on the programmer, which is both advantageous and disadvantageous.

  113. Re:"The fact is..." he's out of touch by Jeremi · · Score: 1
    There is absolutely no construct in C++ you can make that I can't do in C.


    There is no construct in C++ that you can't do in Visual Basic, or a shell script, or any other Turing-complete language either. That's not the point. C++ isn't there to make writing complicated things possible, it's there to make writing complicated things easier. The easier and more fool-proof a given piece of functionality is, the more work you can get done in a day, and the more code you can write and debug in a year. That is the advantage of C++ over C.


    C++ has no concept of "interrupt context", it has no concept of "preemptible
    code", it has no concept of per-CPU data structures.


    Neither, to my knowledge, does C. Those are both policies that must be followed manually by the programmer -- neither a C++ nor a C compiler will do the work for you there.

    --


    I don't care if it's 90,000 hectares. That lake was not my doing.
  114. Hello - are we judging devphil, or the patch here? by Spy+der+Mann · · Score: 1

    Don't consider devphil a kernel developer - more like an apologist (first ammendment anyone?). What we're discussing is the worth of the PATCH, not of people who defend it (that would be an ad-hominem attack - similar to the FUD spread by SCO and Microsoft).

    So please rephrase your statement.
    Current OS kernels created by Linus: 1
    Current OS kernel patches created by Gylfason et. al: 1.

    That makes it even. Also remember that Linus just gave BIRTH to the Kernel. Hundreds of other programmers nurtured it and made it what it is now (can the Mozilla project, for example, be said to have been made by only one man?)

    So please stop idolatring Linus and saying that his word is inspired by God or something. Remember that when he designed Linux, he was trying to improve an existing OS. Who says that nobody can improve his work? Let them try, if it succeeds, it'll be "A better Linux than Linux", just as Linux was "A better Minix than Minix".

    I'm sure that Linus' ideas were revolutionary at his time - but what if he fell short in his design? (GASP! Blasphemy!) Who knows what ideas might have been a huge success had they been implemented in Linux in the first place? (Idea for a poll: If you could go back in time and change something in Linux, what would it be?)

    So, at least give the guys from Reykjavík the benefit of the doubt.
    (Unless of course you want to patent Linux and forbid all innovations on it)

  115. Re:"The fact is..." he's out of touch by ComputerSlicer23 · · Score: 1
    Why is it everyone wants to bring up Turing machines like I have no idea what they are... Grr! Look, there is no feature of C++ which has an obvious advantage over the natural C construction in the Linux kernel. Please feel free to rebut that point (I've asked several people to do that, and nobody seems to want to answer an simple direct question, instead they want to explain "Turing Machines"). It won't be as pretty or as directly straightforward as the C construct, but it won't be like attempting to generate something like lexical closures in the C language.

    Most linked lists have been abstracted. In an ugly manner versus the C++ way, but they also take up a heck of a lot less space then the C++ way using a naive implementation (with partial template specialization, you might be able to not use up any extra memory, but I believe the kernel doens't keep pointers to nodes in the lists, they keep the nodes in the list with the void *next being the first element of the structure).

    Iterating over the lists is abstracted.

    Virtual functions are an essential construct to the linux kernel (see the VFS).

    Namespaces would be very, very nice to have in the kernel, but the kernel handles that by prefixes, and by linking everything in a subsystem into one .o and having specific entry points into that .o and then forget the rest of the symbols to avoid symbol collision between subsystems.

    Classes aren't strictly necessary. As a general rule, by using opaque types, the Linux kernel gets the same types of encapsulation that the C++ class constructs do via this.

    What is needed to improve the Linux kernel, is a language that can allow you to express rules that it needs. Like interrupt context, accessing a per CPU data structure, like recongnizing the locks being misued. Like realizing that you are not using the PCI accessing routines when you should be.

    C++ doesn't do any of those things, and thus in my opinion is not an enhancement in any way to implementing it in C. There are several places where C++ does obscure things (read the standard sometime about resolving overloaded functions and types, even the standard writers aren't sure the rules aren't ambigious or handle all cases sanely). Default copy constructors, operator=, operator==, and the sheer number of places where an exception can be throw (read Exceptional C++ sometime), can all cause problems. Most of the really good stuff in C++ like the STL wouldn't be usable, as they don't fit the design requirements for datastructures in the Linux kernel (see all the standard libc stuff that is re-implemented in the kernel).

    The tools that Linus is working on (which I've always wanted to write, both for the Linux kernel, and for projects at work), are the types of tools you need. Generate a call graph. Do static flow analysis and see if any rules are violated (did you call something which could call "schedule" where is unsafe). Did you call something that requires you hold a lock, while you don't hold the lock. Those are the types of tools and the functionality that will make the kernel better. More crappy type-checking, templates, and RTTI won't do any good. Generating tools which do the code flow analysis is much, much easier in C then it is in C/C++ code. Those will help generate better higher quality source in a much more measurable way then just allowing C++ to be used in a large body of software that it wasn't designed to be used in.

    Kirby

  116. It's just discipline by Julian+Morrison · · Score: 2, Insightful

    You can do stupid juvenile garble in C too, like rewrite the reserved words with #define macros. You don't because it's dumb and because Linus would laugh his ass off and tell you to throw it away, go read "C for dummies" and try again.

    Nobody's forcing you to use C++ features where they would be a bad idea.

  117. Re:"The fact is..." he's out of touch by scotch · · Score: 1
    Why is it everyone wants to bring up Turing machines like I have no idea what they are... Grr! Look, there is no feature of C++ which has an obvious advantage over the natural C construction in the Linux kernel.

    Probably because you initially made a broader statement about C++ and C without regard to usability in the kernel. I could quote if for you if you don't want to look back in the thread. The tactic you are demonstrating is frequently known as "moving the goal posts".

    Your knowledge of C++ seems passable, but your failure to mention RAII and destructors, and your apparent opinion that exceptions can be thrown willy nilly (with out regard to standard library usage, without regard to allocator usage, etc), makes me wonder if you've thought about everything. My knowledge of the kernel is poor, however, so I'll admit that you might be right that there is no place for C++ in kernels or kernel modules. But, hell, anyone that says "c can do anything c++ can do" as a serious attempt to disparage C++ probably isn't qualified to discuss it.

    Also, barring some non-standard C-isms the kernel is probably using, and barring any of the rare non-compatible corner cases, you could take the kernel and compile it today as if it were C++. Then, if there was just one feature that made your life easier, and presuming you had the disipline not to employ paradigms and use C++ features that were detrimental (seems safe) to your requirements, you'd have a win. YMMV

    --
    XML causes global warming.
  118. Not Likely by Anonymous Coward · · Score: 1, Insightful

    Oh the new patch might support C++ (and Andrew Morton might not mind it), but Linus Torvalds *HATES* C++ for kernel work. Why? Ever see a destructor function unravel a system part of a context switch? Destructor functions tend to run independently of strict programmer control. It's often touted as a feature of the language. With operating systems though, you need strict control. You even need to use GOTO in places where the (c) programming language fails to meet needed the needs of necessary data structures needed in an operating system kernel. C just happens to be the best programming language currently available for operating system design. It's why Microsoft uses it, Sun uses it, IBM uses it, HP uses it, and just about everyone else. Don't expect operating systems to be written in Java any time soon.

  119. Re:"The fact is..." he's out of touch by Jeremi · · Score: 1
    Grr! Look, there is no feature of C++ which has an obvious advantage over the natural C construction in the Linux kernel.


    Okay, here's one: Built-in constructors and destructors. You can simulate them in C using constructor- and destructor-like functions, but you'll always have to remember to call those functions at the right time, and if you don't, you'll have a bug in your program. With C++ you don't have to worry about that, they are automatically called for you at the proper time.


    As an example, here is a pseudo-code snippet that I don't think you will be able to express directly in C:



    ObjectRef AllocateNewObject()
    {
    ObjectRef objRef(new Object); // it's impossible to memory leak this Object!
    return objRef;
    }

    Note that this function uses a nice reference-counting template class to make it practically impossible for the heap-allocated Object to be leaked, because the Object will be automatically deleted by the destructor of the last ObjectRef that points to it. ObjectRefs can be passed around and copied just like any other value type, with no need to worry about leakage.


    You can do reference counting in C, but you'll have to scatter manual IncRefCount(object) and DecRefCount(object) function calls throughout your code, and chances are pretty good that you'll eventually forget one someplace and end up leaking memory anyway. Because of C++'s constructors, destructors, and templating, I haven't had a problem with memory leaks in years. I automatically get the correct behaviour every time.

    --


    I don't care if it's 90,000 hectares. That lake was not my doing.
  120. Re:"The fact is..." he's out of touch by scotch · · Score: 1
    Your statements represent a gross misunderstanding of what Standard C++ is. Undefined Behaviour (UB) is part of the definition of C++ - it's a statement of what constructs that would normally seem like valid syntax are not valid C++. These constructs have "undefined behaviour" - sometimes it is platform defined, but it's still not part of standard C++. The same hold trues for straight C - there are many constructs in C that might appear to be valid, but are UB, and so are defined as invalid.

    For examle, this is "undefined behavior" in both C and C++:

    int arr[4];
    int i = 0;
    arr[i++] = i;

    In summary, the existence of "undefined behavior" in the C++ and C standards in no way make the compilers implementing the standards "untrustworthy".

    --
    XML causes global warming.
  121. I'll bet it's da JOOZ! by Anonymous Coward · · Score: 0

    Object-oriented programming is just part of the evil Zionist master plan!

  122. Use 'D' instead of C-- by Anonymous Coward · · Score: 0

    'D' is actually a wonderful language, which would have been the next successor to 'C', had Stroustrup not screwed things up.

    'D' is an object-oriented language that takes the best parts of C and C++ and throws away the worst.h

    http://www.digitalmars.com/d/

  123. But give me FORTH in the kernel, by Joseph_Daniel_Zukige · · Score: 1

    and I'll be a happy camper. Maybe even a happy programmer, too.

    (I suppose I'll have to do that myself someday, just to find out.)

    1. Re:But give me FORTH in the kernel, by Anonymous Coward · · Score: 0

      Another really good idea.

      I have never used Forth myself, but I understand that some part of the PCI spec includes forth coded drivers... Furthermore a lot of embedded applications and low level stuff are coded in Forth, so this could definitely be useful.

  124. If it ain't broke.... by holderofthering · · Score: 1

    .....don't fix it.

  125. Re:"The fact is..." he's out of touch by Anonymous Coward · · Score: 1, Informative

    Yes, "undefined behavior" means, "this is not a feature of the language; DO NOT EVER DO THIS, EVER!". That is, it's a syntactically valid construct with no semantics attached to it. Since there is no semantic value in the statement, you should never use it. Just for the record, C has undefined behavior as well. Try the defined behavior of "int *px = 0; int x = *px;" for starters.

  126. opens the door by NateKid · · Score: 1

    to gaming in the kernel...

  127. No!! by Anonymous Coward · · Score: 0

    Oh FFS. Who moderated this interesting.

    You can write bad code in ANY LANGUAGE.

    Read the previous sentence again, to fully understand it. You can write bad code in ANY LANGUAGE.

    The rest of your post made no sense. Sorry. You've never even used C++.

  128. CRC code is unreadable. by Anonymous Coward · · Score: 0

    ftp://ftp.rocksoft.com/papers/crc_v3.txt
    explains everything about crc code.

    Apparently being unreadable to anyone but a math expert is in the very nature of the problem.

  129. And the point is? by kompiluj · · Score: 1

    Well, I agree with you. But what is the point? I mean C++ is _a low level language_ unlike Java, and will perhaps replace Fortran in coming future as the tool for (*cough*) hardcore numerics, feat you cannot expect from both Java and C#. Take a look here.
    I would like answer your parent post at the same time. C++ is not an OO language. Currently emphasis is put on templates. Even programming patterns in C++ are not expressed in terms of classes, but rather in terms of templates. Please, comparing Java and the lot to C++ is like comparing apples to oranges.

    --
    You can defy gravity... for a short time
    1. Re:And the point is? by joib · · Score: 1


      I mean C++ is _a low level language_ unlike Java, and will perhaps replace Fortran in coming future as the tool for (*cough*) hardcore numerics


      I don't think so. There was lots of interest in C++ numerics around the time C++98 was finalized, but to me it seems it never really took off. I think the underlying reason really is simplicity. Writing high performance C++ code with template metaprogramming and all is pretty tricky, and even trickier to debug. By comparison Fortran is a very easy language to learn, way easier than even plain C. Consider that most people writing numeric code aren't computer scientists, so ease of use is certainly very important.

      Of course, if you need maximum performance, Fortran aliasing rules typically helps the compiler produce faster code than equivalent C/C++.

  130. Re:"The fact is..." he's out of touch by ComputerSlicer23 · · Score: 1
    True enough, I didn't make that context clear. However, it's still mostly true (that C can be hornshoed into doing most everything C++ can, RTTI and the stack unwinding being the two most difficult to pull of, partial template specialization, and replacing some of the optimizations that templates can do). Operator overload is nothing but a hidden function call. Public vs private would be hard, but is merely a matter of discipline and careful usage of opaque types.

    C++ can do things that would be very hard to do in C, using C++ without using most of the things in conjunction is just silly. C++ unravels once you say, well, you can't use exceptions, destructors and RAII become less useful (they are syntactically cleaner, but no less assured then below code). If you stop using templates, then operator overload and overloaded functions are just syntatic sugar too.

    The first two things most people say you can't use in the kernel, are guess what? Templates and exceptions. Templates, because the sneakily lead to bloat (using more memory then you realize, I know that between that and inlining functions can lead to some huge binaries relative to the work they are really doing), and exceptions for reasons listed below. I've always found that using RTTI is just a design flaw. Inheritence is pretty cool, but again anyone willing to take the time can accomplish single inheritence pretty easily by just pounding out the code. Multiple inheritence isn't too much harder, you just have to resolve the collisions by hand. Virtual inheritience is probably pretty difficult unless you start doing sick twisted things with unions.

    Most of the C++ functionality is there and it's all interlocking. Like if you don't want exceptions, constructors and destructors are simple:

    #define WRAP( x ) { constructor() ; x ; destructor(); }

    Works just fine in my C compiler. RAII can easily be implemented this way, just write a macro for each one that calls the functions you want called, make it take some more parameters if you want.

    If you give up exceptions, that's all you need barring the usage of a "goto:". If you use goto you better darn well be aware of it (normally in Linux code, the goto is actually used as the error handler, you jump to the thing that releases all of the things you have allocated so far and exit).

    #define LOCK_SECTION( y, x ) { lock( y ); x ; unlock( y ); }

    There's a simple example of RAII, memory allocations could be the same.

    I see exceptions as non-starter in the kernel for several reasons, adding a throw in any number of places can do a whole slew of nasty things if called in the wrong context, along with the fact that exceptions use up additional stack space with is at a premium in the kernel space (4k or 8k depending on the version, it's a serious overhead if you have lots and lots of threads so getting it to a single page was a goal for a long time).

    Plus the kernel wasn't designed for the usage of exceptions, getting it from it's current state, to a state where using exceptions is stable probably not possible in the incremental fashion that Linus would require it to be (lots of small changes that take you slowly closer to being correct is the way to get things past Linus). Just adding exceptions to a normal program in sane fashion is hard, now think about adding it to something that is inheriently multithreaded and has multiple call stacks all of which might deal poorly with catching an exception they've not been programmed for.

    Exceptions can't be added willy nilly. They would simplify things a great deal in some cases (but would require re-writting of a ton of core kernel code to conver it all over). The Linux kernel uses "goto:" as a general rule to simplify error handling inside of the function (all error handling goes at the end just before the last return statement, if you have an error, goto error_handler; then the error gets passed back up the call chain, un

  131. EROS is dead by Animats · · Score: 1
    The last release was in 2001.

    I liked some of the ideas there, but it's not happening.

  132. One problem by mqRakkis · · Score: 1

    There is one problem though; end-users. As long as they are concerned, it doesn't matter what language the kernel is written in, only speed matters. So even if using C++ is only 0.1% slower than using C, but much nicer to use and maintain, then it's still a loss for the end-user.

  133. Read that again. by warrax_666 · · Score: 1
    If an object is in scope, it's in a clean state. If it's not in scope, it's not.

    Incorrect. If you get a CannotReadMoreException while running the code snippet the GP gave, you have no idea whether or not "string" has an appropriate semantic value -- Note that it was declared in another scope and may even have had other values assigned to it! You can mitigate this type of thing slightly by having appropriate destructors for the variables in question (and never using pointers directly!), but handling this is a lot more tricky than it seems at first. This is in fact one of the reason exceptions suck: they hide a lot of the context of which an operation failed. If you want to know which operation failed, you have to have try { } blocks around each operation and you have to introduce more scopes simply because of the way statement sequences work. This makes code incredibly ugly, which is why many people don't do it, leading to subtle bugs.

    There are lots of things which simplify error handling in C++ (like destructors for automatic variables), but I have this sneaking feeling that strengthening the data types of C (or C++ for that matter) into having types like "Success $RESULT" and "Failure $SOMETHING" and forcing people to looking at return values might have a much greater effect and be more readable in the end...
    --
    HAND.
  134. Re:"The fact is..." he's out of touch by Anonymous Coward · · Score: 0

    Making C-programmers write C++ is not the way to make stuff easier.

    If you want to write C++, go ahead. But keep it out of the kernel, which is written an maintained by mostly C-prople.

  135. Re:"The fact is..." he's out of touch by Anonymous Coward · · Score: 0

    G++ is part of GCC.

  136. I have no problem with this by ChrisMDP · · Score: 1

    ...as long as kernel hackers use the best bits of C++ (default parameters, OO paradigm, late declaration of local variables, const correctness), and leave out everything that could cause problems (virtual functions, inheritance (especially MI), exceptions).

    But that's not going to happen. Give people the tools and they will use them (badly), so we'll end up with a flurry of rejected patches and signal/noise ratio will plummet.

    Stick to C.

  137. You obviously have little real world experience by Viol8 · · Score: 2, Insightful

    "If someone tells me that they are a C/C++ programmer, I'm going to assume they're a novice at both languages."

    Thats an assanine statement to make. I've been a professional programmer for 11 years, most of that doing C AND C++. Yes thats using both languages or a mixture of the 2 depending on what project I've worked on. And I'm quite happy doing either high level OO template programming (C++) or low level boolean bit operations, memory management, function pointers etc (C). Most people I know who do C/C++ would have the same ability and most people I've interviewed myself I would expect the same off. If they can't handle malloc & free they're as useless to me as if they can't handle temaplates.

    "in my head I know that the interview is probably already over."

    Then I suspect you're probably responsible for your company not hiring a lot of good people since you obviously have an arrogant attitude and give the impression that only you can be master of both. If you worked for me I'd never let you near an interview room.

    1. Re:You obviously have little real world experience by jgrahn · · Score: 1
      I've been a professional programmer for 11 years, most of that doing C AND C++. Yes thats using both languages or a mixture of the 2 depending on what project I've worked on.

      Yeah, but would you really lump them together in an interview situation? Would you keep doing that when the interviewer tried to go down on a more detailed level? I have the same feeling as the grandparent -- the phrase "C/C++" is a buzzword the PHBs use because just "C" sounds old-fashioned. Of course that doesn't mean that people who use it must be ignorant, and of course it doesn't mean that using one language well prevents you from using the other one well.

    2. Re:You obviously have little real world experience by swillden · · Score: 1

      I've been a professional programmer for 11 years, most of that doing C AND C++.

      And notice... you didn't say C/C++, and you distinguished between the different forms of C and C++ programming. That's the sort of thing I expect of someone who actually does know both languages.

      you obviously have an arrogant attitude and give the impression that only you can be master of both.

      You must have read someone else's posts, not mine. I never said, nor implied, that "only I can be master of both". What I said was that programmers who know both distinguish between them. Someone who claims five years experience but considers them the same thing is either stupid, or lying. In neither case would I want to hire such a person.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  138. Bzzzt wrong. IMNSHO by Oestergaard · · Score: 1

    C++ is transparent - to anyone who understands the language.

    Just like C is transparent to anyone who understands the language.

    Neither language is transparent to those who do not understand. "Det er da ikke så svært at forstå, er det?" (see what I mean ;)

    Read:
    C vs C++
    written by yours truly.

    The major points in that article in relation to C++ in the kernel will be
    *) Rewriting good C to C++ will be bad C++ and that's not a change to the better
    *) Few (good kernel-) developers understand C++ or are willing to learn

    However, it is interesting to see that Linus is working so much with the SParse tool - which, really, is just a type checking tool allowing to check annotated C types more strictly than the C language itself allows. This is one of the major benefits you get from C++ (and you can get this benefit with *zero* overhead compared to C - the stricter type system does not force you to use features that have overhead). Instead of developing SParse and running type checking in two steps (first the C compiler, then checking with SParse), they could move to C++ and have it all (and then some) in one go.

    But again; I don't think rewriting the kernel to C++ would be reasonable - however, if you start up a new kernel project today, you'd be insane not to go with C++.

    My 0.02 Euro on that one ;)

    1. Re:Bzzzt wrong. IMNSHO by bogado · · Score: 1

      Well I must I liked your "c vc c++" article, but you yourself stated the main problem I see with C++. The incapacity of knowing what is happening behind the scenes. What if you're programing in a plataform with a good STL and when you happen to deploy the program it has am awful implementation? You will never know what have hit you, since it was not your code.

      Well in resume in the C++ world, and in many higher level worlds you're much more dependent in the tools you're using. This is good for one side, since the tools do some hard work for you (like templates), but it has a bad side also, since you never know when you gona step in a problem with the implemantation of tool it self and have your hands tied.

      --
      []'s Victor Bogado da Silva Lins

      ^[:wq

    2. Re:Bzzzt wrong. IMNSHO by Anonymous Coward · · Score: 0
      My problem with C++ is that 95% of self-described "strong C++ programmers" can't even figure out how function overriding _really_ works in C++.

      I'm not exaggerating. I ask every Senior C++ developer I inteview this Interview Question; and to date, only 1 out of well over 100 programmers could answer it correctly. And that one? He explained "yeah, I just read Herb's book last night studying for this".

      Give a non-C++ programmer that question and 0% will get it right. Give these same people Java or C# or C or Eiffel or ML or Haskell or Python or anything except C++ or Perl and they'll probably guess correctly what will happen even if they don't "know" the language well.

      If you have a language where 95+% of people who describe themselves as Sr Developers with Strong Knowledge of the Language can not even figure out which functions in a 20 line program get called; it's the language that sucks, not the developers.

  139. Obligatory Quote by zerojoker · · Score: 2, Funny

    Object-oriented programming is an exceptionally bad idea which could only have originated in California. (Edsger Dijkstra)

  140. Nope by Anonymous Coward · · Score: 1, Informative

    C solves the same problems as C++. It makes different methods of solution easier.
    In many problems, the best solution is a procedural function. In some, it is an OO design. I've written polymorphic functions (badly, admittedly) in Fortran 77 with VAX extensions %REF and %LOC. C++ makes it *easier* to do this.

    One of the cardinal sins of the new C++ programmer is making *everything* an object. Makes the program impossible to debug.

    Two things bug me, though, in combination:

    Function Overloading is NOT recommended for the New/Delete functions. That is the ONE place I would see great benefit from overloading. You can write your own pooling mechanism, ad reference counts and so on by overloading the new and delete function. Why not?

    1. Re:Nope by I_Love_Pocky! · · Score: 1

      C solves the same problems as C++. It makes different methods of solution easier. In many problems, the best solution is a procedural function. In some, it is an OO design. I've written polymorphic functions (badly, admittedly) in Fortran 77 with VAX extensions %REF and %LOC. C++ makes it *easier* to do this.

      What do you mean nope? You didn't write anything that disagreed with me. The post I replied to said C and C++ solved different problems. I said they solved problems differently (as in they can both solve the same problems, but they can sovle them in different ways). If you are trying to say that C can solve problems the same way as C++ just because you could implement OOP in C, I guess you are technically right. Why in the world would you do that though?

      One of the cardinal sins of the new C++ programmer is making *everything* an object. Makes the program impossible to debug.

      Ok I can agree that it is overkill to make everything an object, but how does it make it impossible to debug?

  141. Templates by wtd · · Score: 2, Informative

    You miss what is probably the biggest advantage of C++ (and possibly one of the most controversial).

    Templates allow for some incredibly slick code, and vastly improve both programmer productivity and type safety.

    1. Re:Templates by I_Love_Pocky! · · Score: 1

      I didn't miss templates, I didn't mention them because I feel they are an extension to classes. My post was in response to a post that suggested there was nothing in C++ that wasn't in C that didn't have something to do with classes and inheritence.

      I just thought of one important thing I didn't mention however, and that is name spaces. If you wanted a reason to basicly write straight procedural non-object-oriented C code in C++, name spaces alone could be reason enough to do that.

    2. Re:Templates by EsbenMoseHansen · · Score: 1
      I didn't miss templates, I didn't mention them because I feel they are an extension to classes. My post was in response to a post that suggested there was nothing in C++ that wasn't in C that didn't have something to do with classes and inheritence.

      Template function are quite useful, and do not have anything to do with OO. E.g.

      template<typename T> void swap(T& a,T& b) {
      T tmp(a);
      a=b;
      b=tmp;
      }
      --
      Religion is regarded by the common people as true, by the wise as false, and by rulers as useful.
    3. Re:Templates by I_Love_Pocky! · · Score: 1

      Good point, I hadn't realized that (I admitedly don't use templates).

    4. Re:Templates by wtd · · Score: 1

      I think they're even more powerful when used to replace function pointers.

      #include <string>
      #include <sstream>
      #include <iostream>

      char upper_case(char input) {
      if (input >= 'a' && input <= 'z')
      return input - 32;
      else
      return input;
      }

      template <typename T>
      std::string transform_string(std::string str, T func) {
      std::stringstream ss;
      for (std::string::iterator i(str.begin()); i != str.end(); i++)
      ss << func(*i);
      return ss.str();
      }

      int main() {
      std::cout << transform_string("hello", upper_case) << std::endl;
      return 0;
      }

  142. What about Visual Basic in the kernel? by nickos · · Score: 1

    nt

  143. C/C++ by BenjyD · · Score: 1

    OK, I skipped C out completely and went straight to C++. So my knowledge of pure C is pretty shaky. One (overly long) question:

    Say (for example) I have a program that needs to access, as flat files, data stored in several different formats, each requiring different access methods. I want to minimise the amount of code, obviously. So in C++, I write:

    - a File class with the common code and interface (read_data,write_data,open etc)
    - derived subclasses for each type of file that actually does the reading/writing(DatbaseFile, VFSFile etc.)
    - a manager class that only knows about File classes, not the subclasses
    - some factory class that returns an object of the correct File subclass

    That way, I keep most of the file access code generic and all the filetype specific code is in one place.

    My question is: what is the equivalent of this in C? AFAIK, you'd have to either use switch statements everywhere or some kind of function pointer system. Is there a better alternative? I assume there must be, and I just don't know enough C.

    1. Re:C/C++ by BCoates · · Score: 1

      "some kind of function pointer system" is the usual answer. you basicly roll your own C++ virtual-function table.

  144. Please read: Java Kernel is already there by Anonymous Coward · · Score: 1, Interesting

    I really hope this gets somewhat modded up.

    There IS an OS kernel that is written in pure java - and it actually makes sense!
    It is developed at my university in Erlangen/Germany and called JX.

    http://jxos.org/

    At first I also thought "Bah, screw it". But more interesting is the DESIGN and the on-the-fly merging of domains, which I consider the most interesting _concept_ ever!

    Please see their website for actual implementation designs and benchmarks.

  145. MVS, not VMS by WindBourne · · Score: 1

    Sorry, you are right. It was MVS that I saw. damn transpositino

    --
    I prefer the "u" in honour as it seems to be missing these days.
  146. Re:"The fact is..." he's out of touch by devphil · · Score: 1


    I think it's unreasonable -- and dishonest -- to say that <some tool I have no relevent experience with> is untrustworthy.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
  147. Re:"The fact is..." he's out of touch by devphil · · Score: 1


    So does C, and every other language derived from it. That changes nothing.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
  148. You have no idea what OO is all about. by Kickasso · · Score: 1

    OO paradigm yes, virtual functions no? Stick to C.

    1. Re:You have no idea what OO is all about. by ChrisMDP · · Score: 2, Insightful

      I respectfully disagree, having spent several years of my life coding C++ and Java professionally.

      There's more to OO than mere polymorphism. Encapsulation is a very useful feature in its own right. By 'could cause problems', read 'could cause problems in kernel development'. For example, virtual functions require lookups and dereferencing at runtime, and the vtable arbitrarily increases the size of an object, both of which are undesirable in kernel development.

  149. Weak symbols in C++? by a_hofmann · · Score: 1

    A question that occured to me while reading the article:

    Why are C++ compilers normally using string comparison on type checking? The taken approach of pointer comparison seems to be the logic choice in the first place, so I wonder why this is often done the other way.

    I remember something about linking and shared libraries, but an obvious problem doesn't come to mind...

  150. Lisp in the Linux kernel by srenker · · Score: 1

    I think this discussion is missing the point. The only true computer language is Lisp! C++ is teh sux0rz!!1!

    --
    My new /. login is fabu10u$.
  151. Polymorphism is not necessarily call-by-pointer by Chemisor · · Score: 1

    > This will compile to an indirect-branch (to figure out which class to use at run-time)

    Not necessarily. If you implement your call as virtual and give your function a class pointer, then of course that is what will happen. In C you would have to do the same thing for similar functionality. But you do not have to do this. An non-virtual inline operator= will always produce a simple or and store, just like the original C code. The difference is that you have now abstracted the interface from implementation and can substitute another implementation without changing the original code. That is what C++ is all about and it is an enormous benefit if you ever need to modify your code.

    1. Re:Polymorphism is not necessarily call-by-pointer by akuma(x86) · · Score: 1

      First you say...

      >> In fact, you could transparently support multiple types of registers by overloading operator= of SOMEREG_ptr, which could be a polymorphic class

      And then you say...

      >> An non-virtual inline operator= will always produce a simple or and store, just like the original C code

      Well, if it's non-virtual, then it isn't polymorphic is it? You would have to know the type of your register at compile time.

    2. Re:Polymorphism is not necessarily call-by-pointer by Chemisor · · Score: 1

      > Well, if it's non-virtual, then it isn't polymorphic is it?

      Then it is compile-time polymorphic. It's something you would use in a template, for instance. I am simply addressing your original complaint of a store becoming a virtual function call. If you don't need it, don't do it! I was saying that the capability is there if you need it, and if you look at the kernel code you will find plenty of places that do. Yes, you incur overhead, but lots of times it pays for itself in cleaner design, and if you don't do it in a time-critical loop (there aren't as many of those as you think), nobody will notice a few extra cycles. As for compile-time class selection in a template, it is much better than cut-n-paste code (or macros, for that matter) that you would have to do in C.

    3. Re:Polymorphism is not necessarily call-by-pointer by akuma(x86) · · Score: 1

      I guess you don't understand what polymorphic means. It is specifically meant to be determined at run time - hence it is also called late-binding in the literature.

      Sometimes it is impossible to know at compile time because the type you are using may be a function of runtime parameters - templates or not.

      The problem with C++ in the kernel is also it's strength in other kinds of apps. By hiding implementation details behind abstractions and interfaces, you don't understand how things work under the hood unless you peel back the layers of abstraction to look inside.

      Transparency is needed for kernel code.

      A = B + C is ambiguous in C++. You need to dig deeper into the various class heirarchies to figure out what the machine is really doing at the lowest levels (like kernel code) -- which defeats the purpose of the abstraction in the first place. The kernel is controlling the machine at the lowest level. It is almost by definition at the bottom of the stack of abstractions and interfaces - so wrapping it up in layers that obfuscate it's core functionality doesn't make sense.

  152. Gadget interfaces produce minimal code by Chemisor · · Score: 1

    > The point is that people like you delight in
    > creating gadget interfaces, and avoid minimal,
    > repetative, direct programming designs.

    A good "gadget" interface will produce your "minimal, repetetive, and direct" code, but with less effort. More abstraction does not necessarily lead to more code. Consider the following:

    class CDevice {
    public:
    CDevice (SOMEREG_ptr* pRegs) : m_pRegs(pRegs){}
    inline void EnableFeatureX (void) { *m_pRegs = BIT_A | BIT_B; }
    private:
    SOMEREG_ptr m_pRegs;
    };

    CDevice dev (GetDeviceRegs());
    dev.EnableFeatureX();

    This code will compile to a copy to a local variable (the constructor), an OR and a memory store, just as your original code did. There is absolutely no extra overhead. But now you see exactly what the code wants to do. BIT_A and BIT_B do not necessarily mean much, and you would have to add comments all over the place. In C++ the code can be much more self-explanatory, which means that maintainers would not have to dig through documentation as much. And then consider what happens if you have to add |BIT_C to EnableFeatureX. If you wrote this in C (which normally does not support inline functions), you would have to change every occurence of setting BIT_A and BIT_B. In the C++ implementation you change it in one place and you are done.

    1. Re:Gadget interfaces produce minimal code by Abcd1234 · · Score: 1

      If you wrote this in C (which normally does not support inline functions), you would have to change every occurence of setting BIT_A and BIT_B

      Umm, huh?

      inline void enableFeatureX(SOMEREG_ptr* pRegs) {
      *pRegs = BIT_A | BIT_B;
      }

      Or, alternatively (and probaby more portable across compilers):

      #define ENABLE_FEATURE_X(regs) *(regs) = BIT_A | BIT_B;

      Perhaps you should have picked a better example.

    2. Re:Gadget interfaces produce minimal code by Chemisor · · Score: 1

      > Umm, huh?
      > inline void enableFeatureX(SOMEREG_ptr* pRegs)

      Like I said, inline functions in C is a gcc extension, and is not portable. You could do it by declaring the function as static, in which case the compiler will almost always expand it inline, but that only works in one file, so mostly you will see things like that done with macros.

      > #define ENABLE_FEATURE_X(regs) *(regs) = BIT_A | BIT_B;

      This will not catch stupid type mistakes like this:
      int* reg;
      regs = GetRegs();
      ENABLE_FEATURE_X(reg);
      Type safety is a good thing. It saves you time by not letting you do with your types what you did not want to do with them. Macros have other problems, like not being visible in the debugger, unlike inline functions which can be stepped through.

      These are only minor annoyances though compared with the scoping problem. In C++ CDevice::EnableFeatureX is clearly associated with CDevice, which represents a specific interface. All functions in CDevice compose that interface and are naturally aggregated in both space and scope. The C function in your example is an algorithm operating on SOMEREG_ptr*, which gives the developer no clue as to what interface this function belongs. A C interface simply can not look as coherent as a C++ class because the language can not encode that type of information. It also can not encapsulate information about the device within itself. enableFeatureX depends on the internal structure of SOMEREG_ptr, which for this reason must remain exposed. A C++ class can keep internals to itself and expose only the functionality that is needed outside, allowing change of internal implementation without modification of client code. Of course, this is not a limitation for small programs, such as most UNIX command line stuff like ls, mv, rm, etc., but it becomes a larger problem the larger your project grows, possibly becoming a tangled mess of components reaching into each other where they are not supposed to.

    3. Re:Gadget interfaces produce minimal code by pthisis · · Score: 1

      inline functions in C is a gcc extension, and is not portable
      1. All reasonable C compilers (and most crappy ones) have supported inline for many years
      2. Inline is part of standard C since C99.

      --
      rage, rage against the dying of the light
  153. MOD PARENT UP by Anonymous Coward · · Score: 0

    It's interesting

  154. You are right, however ... :) by kompiluj · · Score: 1

    OK, you are right, there seems to be really not much happening on both Blitz and Pooma homepages. And of course Fortran is oriented towards HPC, that's obvious, and is much easier than C++. What I wanted to say is, perhaps, that C++ _could potentially_ replace Fortran as the high performance computing language of choice, whereas Java still cannot and it does not seem that it will in near future. Therefore ,in my opinion, people comparing Java to C++ in terms of performance are comparing apples to oranges.

    --
    You can defy gravity... for a short time
  155. enough crack for me today:( by Anonymous Coward · · Score: 0

    s/function overloading/function overriding/
    s/operator overloading/function overloading/

  156. Re:"The fact is..." he's out of touch by RedWizzard · · Score: 1

    If you're refering to Linus, he does have experience with G++. I'd also point out that Linus does (deliberately) overstate arguments on LMKL. He may not have said that quote you're reacting to "with a straight face".

  157. fuck you by pyrrho · · Score: 1

    I happen to have been reading Stroustrup on the History of C++ recently, and he is the one that paints C++ this way.

    so fuck you unread bigot.

    did I mention fuck you?

    C++ is an improved C, choke on it. read a book.

    --

    -pyrrho

  158. with-less-anger version by pyrrho · · Score: 1

    I like the forumlation that it throws C in an OOP direction, except that the STL isn't oop, and strong typing isn't OOP, although it's realated.

    Seriously, read History of C++ and you will understand the lengths gone to to make C++ C v2.0 compared with... Objective C, etc. etc. etc.

    None of this means the C++ IS Cv2.0, it's not (that would be ANSI C), and maybe there are even better languages that could be C v3.0... but I won't hold my breath waiting for you to create it.

    --

    -pyrrho

  159. The drivers are a major plus by Craig+Ringer · · Score: 1

    Seriously. The fact that one can simply build and install a Linux kernel and _already_ have all the drivers required is IMO very important.

    I really don't like the idea of having to go online and download drivers, and if the drivers were availible as another bundled download, really what would be the point?

    Anyway, I don't really see how separating drivers from the kernel core could make sense given the Linux development policy on stable driver APIs (that is, there aren't any).

    1. Re:The drivers are a major plus by jedimark · · Score: 1
      I agree that it is damn handy having everything at your fingertips... But I was kinda refering to a fair bit into the future of linux. (well, hopefully not too far away)

      With a restructure and perhaps the benifits of using a little C++ in the driver/module interface we could make a decent API available.

      Something like a standardized driver source code repository would be awesome. And a little front end app to fetch and build... (emerge anyone? ;-) Distributions can play a key role here if they dont sh*tfight with each other over and actually adpot something.

      This seems to be a major problem with Linux - the forces that be are a little too slow to standardize on anything.. (apart from the apparent "rejection of new ideas" standard ;-) IMHO the linux kernel is stagnating a little bit in this area..

      Still, theres not much better to use at the moment, so I will stick to what we got... At home, I have 10 gentoo boxen for development, and 1 mac running OS-X. It'll be running gentoo too the second my wife turns her head... ;-)

      Debian rules too, but just not in my house. :-)

    2. Re:The drivers are a major plus by Craig+Ringer · · Score: 1

      I really don't see a stable driver API happening, though. One can write a stable API in C as well as C++ - but the kernel folks explicitly choose not to. I can understand why, though I won't get into the endless arguments about the merits of the decision.

      Also, regarding the difficulty of getting drivers - it's not, to me, a matter of having them easy to install. It's that they're /already there/. No 'net access required, no stuffing about with boot-time driver disks, it just works. I suppose one could provide tools to download and build all the drivers, but I just don't see the attraction vs the current scheme while the drivers are so closely bound to the kernel core.

  160. what you're missing by pyrrho · · Score: 1

    Stroustrup et al took great care to make sure the C++ be able to solve all the same problems as C, even to the degree that C code compiles pretty much unaltered (a couple exceptions, generally regarding typing issues).

    C-style is ONE OF THE PARADIGMS available in C++, and if you use it, you get no "C++" overhead. That's by design. Please note all the other languages that DON'T take that approach. It wasn't an accident.

    --

    -pyrrho

  161. C++ as Better C by pyrrho · · Score: 1

    meaning without the OOP stuff.

    function polymorphism is one of the main advantages to writing C-style in C++. It's nice to share the name of the function but have versions that take different arguments.

    --

    -pyrrho

  162. where did it come from by pyrrho · · Score: 1

    and why did these C++ features keep making it back into C?

    The answers have been available in print for more than ten years.

    sorry, that other guy got me worked up.

    --

    -pyrrho

  163. Re:"The fact is..." he's out of touch by Anonymous Coward · · Score: 0

    "this is not a feature of the language; DO NOT EVER DO THIS, EVER!"

    That's a gross overstatement. You don't write stuff like kernels without going UB.

    #include <kernel.h> is undefined behaviour.
    if (p<q) is undefined behaviour if p and q are pointers and don't point to the same "address space".
    type-punning is usually an undefined behaviour.
    casting a function pointer to a void pointer is undefined behaviour.
    int __foo is undefined behaviour.
    poking data at random memory addresses is undefined behaviour.

    Even in system-dependent modules. UB is UB is UB.

  164. templates in C++ by pyrrho · · Score: 1

    I assume there is some terminological collision here.

    "templates" in C++ refers to it's typesafe generic programming...

    --

    -pyrrho

    1. Re:templates in C++ by Craig+Davison · · Score: 1

      Oops, you're right. I was thinking of interfaces (in the Java sense of the word). Don't know how I confused that with templates.

    2. Re:templates in C++ by pyrrho · · Score: 1

      it's a natural language meaning.

      computer science has a way of not only creating new words, but then using them for different things.

      a funny one I've watched over the years is polymorphism, so often people think they know what it refers to but the bigger picture is it's used to mean many things.

      polymorphism where functions taking different arguments are different forms... but also the idea of using classes as ancestor classes, and a few more, all coming down to the general natural language meaning of anything that takes multiple forms.

      "template" is not really the right term these days, the unifying term is "generic programming".

      --

      -pyrrho

  165. thanks by pyrrho · · Score: 1

    you just lowered my blood pressure. :)

    --

    -pyrrho

  166. although it's a generalization by pyrrho · · Score: 1

    it's true.

    C++ is multiparadigmed.

    You can use pointers. But you can also adopt a standard where you do not have to use pointers (generally you will manipulate pointers at lower levels, say in class libraries you make or purchase). You can't adopt a "pointerless paradigm" for an application project, and then go use pointers.

    You can use printf style string building and stream style, but it's better to choose one and use it.

    RTTI: yes... and if you grant that some projects really do need/want RTTI, then this is a conflict with the possible paradigm of relying only on compile time type checking.

    You can have a paradigm where constructors cannot fail... i.e. you can set defaults and prepare your class, but you might avoid mallocing or attaching to streams, etc., in your constructor, instead putting that into an "init" type function. That's legit, it's also legit to do it in constructors (assuming you don't mind using exceptions to handle errors in the constructor), but doing both in one project is not a clear approach. Goto is available in C++... and you might use an old fashioned error handling system using goto:, exceptions are probably better, but the former is still legal C++ and if used for whatever reason, should not be mixed also with using exceptions sometimes, and goto at others.

    All of this comes from the fact that C++ is designed to give options to the programmer. And many of these options are contradictory, if not literally incoherent when used together, use of them together shows a lack of design, show that there is no design, or at least that there is a mixed and therefore unclear standard at use in the code.

    --

    -pyrrho

    1. Re:although it's a generalization by Progoth · · Score: 1

      so what you're saying is that mixing "real C++" and "C with classes C++" is bad. Mostly. Yes, I agree. Of course, I don't think that in most cases you should use C-isms at all.

      I say if you want to use C, then use C. If you want to use C++, then use the standard library, use streams, use references, use exceptions, and you'll get out better code more efficiently.

  167. C++? Why no love for... by l4m3z0r · · Score: 3, Interesting

    Whats wrong with objective-c. I would consider that to be a much more viable option for adding object support into the linux kernel because thats basically what we are talking about. Without objects C++ offers no real benefit over C and in fact with the absence of objects is a detrement. Objective-C on the other hand is pure C with some nifty object support stapled on. Way better and in my opinion much more likely to be accepted by them kernel folks.

    1. Re:C++? Why no love for... by dooglio · · Score: 1

      I've never used Objective-C before, but it sounds like it's kinda like "C++-lite". It seems to me that taking advantage of stack-based construction/destruction would be a big plus-- esp for resource management.

  168. yeah by pyrrho · · Score: 1

    but what I said is still true. That sort of thing has been kept for a minimum.

    It's legit to say "not minimum enough" and my OOPers would happilly say compatibility is "way too minumumly broken", but there is no doubt that there has been a very real attempt to keep it as minimal as possible.

    --

    -pyrrho

  169. i was driven to it! by pyrrho · · Score: 1

    or maybe it was a different set of mistakes!

    a continuation of it is ideal

    it is evolution which has been drivien

    --

    -pyrrho

  170. Look up prolog tabling. by Baldrson · · Score: 1
    See prolog tabling.

    It is simply a matter of how eager the evaluation is, but the table can be generated prior to execution if the predicates are known at compile time. If you dislike how efficient the tabling mechanism is in, say, XSB prolog, then you always have the option of building an optimizer for a particular machine.

  171. Why do I have to do everything? by Chemisor · · Score: 1

    Obviously, you are not going to be convinced until I go and actually write a C++ compiler. Of course, that is the only answer possible these days to any software problem. Linux has no desktop? Quit complaining and go write one! Linux has no games? Shut up and go write one! C++ compilers are impossible? Why don't you go and write one! Yes, proof by accomplishment really is incontrovertible, but it is sad that it is the only one left. Sure I can write a few good programs, and I am, but it will take many years for me to write everything, even if I were interested enough to try. What I wonder, is why am I the only one charged with this task? Why doesn't somebody else say "It can be done!" and do it? Where are the confident people who do instead of profess the impossibility of doing? Where will the world go if it is overrun by the latter?

  172. Model theory and computers by Baldrson · · Score: 1
    Model theory is the study of formal languages in regard to mathematical objects.

    If you were to say a computer's instruction set was not a mathematical object, you would hear objections from mathematicians like Alan Turing.

    If you were to say a computer's circuitry was not a mathematical object, you would hear objections from mathematicians like George Boole.

  173. Huh? by Kickasso · · Score: 1

    Encapsulation is useful indeed, but OO it doesn't make. Ada has encapsulation, but nobody calls it OO. "Virtual functions" is a fancy name for a table of function pointers. It's a useful method of managing your control flow, and one that is used in the kernel as well, nothing new here. An object with an integer type field is just as big as one with a pointer to vtbl, you chose one or the other.

  174. The expressive power of equality. by Baldrson · · Score: 1
    I'd appreciate your thoughts on the following, as I think it may provide a better way to approach modeling computer systems:

    Quine, in his essay "The Scope of Logic" says the identity predicate x=y is inherent in the very idea of predicates.

    Given the predicate P(x1,x2,x3,...xN), a "Quine identity" P(A=B) is the conjunction:

    For all x2,x3,...xN ( P( A ,x2,x3,...xN) iff P( B ,x2,x3...xN) &
    For all x1, x3,...xN ( P(x1, A ,x3,...xN) iff P(x1, B ,x3...xN) &
    For all x1,x2, ...xN ( P(x1,x2, A ,...xN) iff P(x1,x2, B ...xN) &
    ...
    For all x1,x2,x3,... ( P(x1,x2,x3,... A ) iff P(x1,x2,x3... B )

    Tom Etter (yes, the author of Racter) posits three predicates about which nothing is presumed except that they are Quine identities:

    Row(x=y)
    Column(x=y)
    Value(x=y)

    Mathematics is now expressible with no further primitives.

    FOR INSTANCE:

    See The Expressive Power of Equality for a proof that three identities are sufficient to express Zermelo-Fraenkl set theory.

    1. Re:The expressive power of equality. by sexylicious · · Score: 1

      Wrong. You need to add your operators to your rules. Otherwise, you just have a bunch of gibberish. (Can't have an equality without a definition of that operator.)

      In other words, you need several axioms just to get to predicate calculus as a viable theory to use. Plus, you'll need to infer a few things about your set.

      Predicate calculus can define most of mathematics, but not without some help from more rules or a theorem or two (Godel's completeness theorem for one).

      Set theory is still a better tool for computers. And the reason for that is because it's a stronger theory (predicate calculus needs help to have a strong enough foundation to stand on, and it lacks hypersets which are inherently natural abstractions of the kinds of sets that would describe a computer).

      Your equality proof is based on some circular logic that makes it a weak proof. And it assumes that a higher set can be derived from a lower set, which can and can not be true depending on your set.

    2. Re:The expressive power of equality. by Baldrson · · Score: 1
      Wrong. You need to add your operators to your rules.

      The point I believe Etter is making is about the appropriate phrasing and location of those rules. He's attempting to deal with the notion of "thing" or ontology and how it relates to physics, which, I think, is quite important to the foundation of any attempt to model computation.

      From a postscript to another of Etter's papers:

      Logic, as currently taught, has three levels.

      Level 1 is the science of pure predication and proof. One of the great achievements of modern times is to have put this science into a form whose principles are as self-evident as 2+2 = 4. This happened in the latter part of the Nineteenth Century, and the people responsible, or at least those whose names we know, had modest aims, mostly having to do with fixing the serious bugs in the Aristotelian logic still taught in the schools of their time. What emerged, however, was a totally new branch of mathematics. This has come to be called the predicate calculus, and it has nailed down once and for all what is meant by logical proof. In essence, the predicate calculus is the grammar of the words AND, OR, NOT, SOME and ALL. What makes it so important is how deeply these rules are embedded in all of human thought. If you believe they are wrong, and you want to convince the rest of us to change them, you had better have awfully good reasons, for to do so would be like convincing us that 2+2 = 5.

      The second level goes beyond those rules that govern predication in general to introduce a particular predicate, the equality predicate x=y. The axioms for equality are normally presented as belonging to logic, and Quine2 has argued very cogently that this is proper. Even if we agree with him, though, we must be clear that the equality axioms are independent of the axioms of "pure" logic at level 1. Level 2 thus has room for changes that don't bear on the rules for AND.

      The third level, and here I am referring to what is found in most logic textbooks, is set theory. Quine3 argues, and again very cogently, that set theory does not really belong to logic, and here I agree with him. Though there have been various attempts to create a quantum set theory, I don't see how changes on level 3 can be fundamental enough to come to grips with complementarity.

      This brings us back to level 2. What I am proposing is that we should found level 2 on a three-place predicate that I call sameness, rather than on the two place equality predicate x=y. My notation for this predicate is y(x=z), read "x is the same y as z". Examples: "2+2 is the same number as 2*2", "Mary is the same woman as Mrs. Smith", "Bill is the same man he was ten years ago", "The morning star is the same planet as the evening star", "Your car is the same color as mine" etc. The axioms of sameness are very simple:

      Axiom 1. y(x=x)
      Axiom 2. If y(x=z) then y(z=x)
      Axiom 3. If y(x=z) and y(z=w) then y(x=w)

      Logical analysis has shown that the sameness predicate has some remarkable properties. For instance, it can be "morphed" into any other predicate by applying suitable axioms; it's the Morpheus of predicates, so-to-speak. Another remarkable fact is that any axiom system can be translated into an axiom system in which sameness is the only predicate. All of this is beyond the scope of the present paper, however; the point here is to see how sameness handles complementarity.

      Suppose we are given q and p such that q(x=z) means that x has the same position as z and p(x=z) means they have the same momentum. Now if we can measure position, then we can tell whether x has the same position as z, and similarly if we can measure momentum, we can tell whether x has the same momentum as z. Therefore if we can simultaneously measure both position AND momentum, we can tell whether x has the same position AND the same momentum as z. Thus the question arises as to whether this compound of two samenesses comes under the a

  175. What you are suggesting... by Ayanami+Rei · · Score: 1

    what you are suggesting is more along the lines of emulating the linux syscall API and scheduling model as a replacement set of APIs for java code (the ported linux userland programs).

    That'd be really strange to behold, and the amount of work recoding everything in java would be enormous. Not to say you couldn't emulate it all from a non-developers' user's perspective, but the source code itself would be shockingly different.

    --
    THIS THING CAN TURN ON A DIME, MACROSSZERO STYLE ALSO FUCK BETA, ~NYORON
  176. Erratum: quantifier missing by Baldrson · · Score: 1
    The sentence:

    It does not follow, however, that r such that r(x=z) if and only if Epq(x,z).

    has the existential quantifier before the 'r' in the original pdf, so I should have transcribed it as:

    It does not follow, however, that there exists an r such that r(x=z) if and only if Epq(x,z).

  177. many paradigms are available in C too by pyrrho · · Score: 1

    and you need to choose one for your project and stick with it.

    if you do choose a C style paradigm (a paradigm easily available in C, that is)... why not add to that some of the Better C in C++? Like polymorphic functions, default arguments, generic functions, better static typing, all of which introduce no inefficiencies (at least no more than making efficiency mistakes in regular C does).

    Even simple classes as structures with constructors and destructors are easy to use such that they don't introduce inefficient or "hidden" code.

    --

    -pyrrho

  178. Flawed analogy by warrax_666 · · Score: 1

    One problem with your analogy is that all those languages are (approximately) equally expressive, ie. sentences are not disproportionately more complex in one language over another when expressing the same ideas. However, if there was another easily spoken language which allowed you to condense the story without losing detail/content, wouldn't you use it?

    This is just one fundamental difference between programming languages and natural languages.

    --
    HAND.