7 ms·
Linux kernel coding style
- kakakiki 12y ago"There are heretic movements that try to make indentations 4 (or even 2!) characters deep, and that is akin to trying to define the value of PI to be 3." HA!
- snlacks 12y agoI laughed too. He makes a good point about the amount of indentation in code. As someone who spends most of their time in JavaScript, I see how hard it would be to fit our code to this, and at the same time how much we'd all benefit if we tried to. I just looked at the random JS file on top of my editor... have some refactoring to do.
- kakakiki 12y agoI understand your point. I am having some rethinking about my style of writing too :)
- robinhoodexe 12y ago"First off, I'd suggest printing out a copy of the GNU coding standards, and NOT read it. Burn them, it's a great symbolic gesture." Shots fired.
- bryal 12y agoWith the target being the, what?, 5 people?, that enjoy following the GNU coding standards.
- eyko 12y agoThe Kernel coding style wasn't written a week ago. The first I read it, more than a decade ago, the GNU coding standards did matter and I remember feeling quite hurt by that (in a good way, since I don't think anybody took it that seriously). Matter of fact, the GNU coding standards still matter (to a certain extent) to many of us, and you would be thankful that they did, since it's the basis that provides consistency among GNU (and non GNU) command line apps, for example. The GNU coding standards is an extensive document which doesn't only talk about how to write C code, but also how to talks about how to design software consistent with the GNU principles (command line user interfaces, options, stdin/stdout behaviour, etc). Personally I take the kernel coding style as a whole different thing. It's a short guide on how to write consistent code for the linux kernel. And full of good opinionated choices in my opinion. Its scope is very different from that of the GNU coding standards (which, I'd say, is focused towards writing userland programs which the user will interact with). Also, remember that GNU wanted (wants?) to create an OS, not just a kernel, so I guess we can read their guidelines as something similar to Apple's human interface guidelines for devs :)
- bryal 12y agoI've always thought of the GNU coding standards as an, IMO, ugly and hardly readable way of formatting C code. I didn't realize there was this much to it. Thanks for enlightening me.
- wsc981 12y agoI thought it was a funny read (and I certainly don't agree with everything, even if some snark remarks gave me a good laugh). I wonder if the style guide has been written by Linus, which would make sense to me.
- kagia 12y agoI doubt everyone agrees to that coding style, I certainly don't. However when submitting code to a project I'd still stick to the prescribed coding style, because I believe consistency in any code base can be just as important as any other measure of readability.
- snlacks 12y agoI find it hard to agree with a lot of this, but it'd obviously be someone who's written a lot of code, thought a lot about how to write code, and reads a lot of code - even if we didn't know who it was. There's a lot to learn from reading stuff like this, if you take it all with a grain of salt... or if you're contributing.
- stinos 12y agoThis. It's easier to find lots of people who don't agree with a particular style (I agree with none but mine which is far, far away from the kernel one's for instance and much more readable of course, lol) than people who do, but worse is projects where styles are mixed. Or even tabs and spaces are mixed. Don't get started on that one :] (edit already happened in other comments, of course)
- andmarios 12y agoI think it was written by Torvalds and other kernel hackers. It is part of the Linux source code, under the Documentation directory.
- robin_reala 12y agoInitial commit was by Linus[0], but it looks like most of the other commits[1] have been small amends by other people (apart from a couple of new chapters) [0] https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/Documentation/CodingStyle?id=1da177e4c3f41524e886b7f1b8a0c1fc7321cac2 https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.... [1] https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/log/Documentation/CodingStyle https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux....
- patrickg 12y agoI am glad that for Go there is `go fmt` which predefines some of the issues mentioned in the article. Thus there is "one global coding style for Go". It's another matter if one likes it or not.
- Dewie 12y agoI don't see why there couldn't be a `kernel fmt` tool. In this day and age, we should really be beyond having to worry about things like hmm, what was the brace style in this project again, and should all if/while/for have mandatory braces?.
- qznc 12y agoThat would be "astyle --style=linux" for example.
- maxlybbert 12y agoOr lindent, which I think is mentioned in the kernel style guide (it's a shell script that calls indent with set parameters).
- dezgeg 12y agoSadly, running Lindent on almost any existing source file in the tree will produce dozens of spurious diff hunks due to most other people manually formatting their code, so Lindent is quite useless in practice. It really does bother me how much of the coders' and code reviewers' bandwidth in the kernel community is wasted due to these silly formatting issues. In most IDE-using communities these problems were solved a long time ago, by the IDE autoreformatting your code on commit, with no exceptions.
- qznc 12y agoLinus could easily do "lindent reformat" commit every once in a while or even automate it. It seems they do not care that much for the styleguide?
- raverbashing 12y agoI like it I really prefer using tabs. Having it displayed as 8 spaces in other languages is not as good as in C And they get it right about typedefs in C
- Dewie 12y agoRight, having tabs seems better since I can configure my editor to display tabs as 4 spaces, while whoever else can have tabs be displayed as 8 spaces. Having spaces instead, and having to make your tabs output spaces, and perhaps also backspace deleting four spaces (a "tab") in certain contexts, seems pretty complex in comparison.
- twic 12y agoAgreed. Using spaces to painstakingly emulate tabs, rather than just using tabs, seems absurd to me. Even better, if you use real tabs, you might be able to use elastic tabstops: http://nickgravgaard.com/elastictabstops/ http://nickgravgaard.com/elastictabstops/
- oneeyedpigeon 12y agoAgreed, although this doesn't sit well with me when combined with the reasons for the recommendation - i.e. 8 is just better, line length should be 80, nesting should be limited to 3. If someone can set their indent level to something other than 8, won't they be more likely to violate other rules? I say this having just realised I have my tab set to 4 spaces ...
- dezgeg 12y agoIn theory, it sounds like a nice idea that by having tabs, you could choose your own preferred indent width of something different than 8 columns. But in practice, this will cause problems, such as code written by you going over the maximum line length when viewed by people with 8 column tabs.
- Dewie 12y agoMy editor is set to wrap around on long lines... but that is again of course another thing that potentially has to be tweaked. That is something that is done when writing normal text (like in this text box here on this website), and is done in word processors, so it feels pretty natural. Though I've used that (wrapping around) mostly when writing in Haskell, for some reason. In Java and whatever lines tend to not become too long, perhaps because I tend to use four space indent...
- JBiserkov 12y ago>Encoding the type of a function into the name (so-called Hungarian notation) is brain damaged - the compiler knows the types anyway and can check those, and it only confuses the programmer. No wonder MicroSoft makes buggy programs. "Making Wrong Code Look Wrong" by Joel Spolsky is a must-read and contains an explanation of Apps Hungarian (the original, thoughtful one) vs Systems Hungarian http://www.joelonsoftware.com/articles/Wrong.html http://www.joelonsoftware.com/articles/Wrong.html
- cbd1984 12y agoRight. Use Hungarian to encode information the type system can't represent. This is relevant even in object oriented languages, such as distinguishing between escaped and unescaped strings.
- humanrebar 12y agoC is not a strongly typed language and it does not allow function overloading. C projects should allow for some flexibility in naming notations to make up for those language design decisions. Also, any project that uses int return codes shouldn't be leaning too heavily on type safety.
- juliangregorian 12y agoThis is really interesting. I was about to correct you since I remembered using function overloading, but then I double checked and it was indeed C++. I knew about C++'s name mangling from having coded against it in FFI, but never knew why it existed: the name mangling is what allows C++ to have function overloading. Light bulb!
- kijin 12y ago> spaces are never used for indentation If indentation should always use tabs (0x09) and never spaces (0x20), then the whole rant about indentation width is pointless. Any modern editor will allow you to adjust the displayed width of a tab. It's only when you use spaces for indentation that the width becomes a concern.
- rossy 12y agoWhen you have a limit of 80 characters per line, the indentation width still matters because code that doesn't appear to overflow with 4 space tabs could overflow with 8 space tabs.
- repsilat 12y agoThere are two counterarguments to this: - Line length. Some people say lines should be no longer than 78-80 characters, and you can't reasonably enforce a rule like this without answering how "wide" a tab is. - Alignment. The "right thing to do" is to indent with tabs and align with spaces, but this is difficult for some people, against the religion of others (mixing tabs and spaces!) and insufficient if you want to align text that spans different levels of indentation. If most people use 8-character wide tabs, things will at least look right for them when it inevitably goes wrong.
- davidw 12y agoI'm a fan of the Tcl/Apache/BSD style. Indeed, Tcl has nice C code: https://github.com/tcltk/tcl/blob/master/generic/tclCompile.c https://github.com/tcltk/tcl/blob/master/generic/tclCompile....
- oneeyedpigeon 12y agoNice, but they definitely overcomment IMO, e.g. https://github.com/tcltk/tcl/blob/master/generic/tclCompile.c#L861,L867 https://github.com/tcltk/tcl/blob/master/generic/tclCompile....
- jmnicolas 12y agoAfter having maintained several projects with absolutely 0 comment apart the ones that were copy pasted from examples found on the web, I can tell you there's no such thing as "overcomment".
- why-el 12y agoThen I think you will enjoy this thread. :) http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered http://stackoverflow.com/questions/184618/what-is-the-best-c...
- oneeyedpigeon 12y agoI mentioned it partly because it's addressed in the actual article, and the specific instance I referenced is such a flagrant abuse of the guideline: "Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to write the code so that the _working_ is obvious, and it's a waste of time to explain badly written code." It's almost as bad as: // Increment i i++; I think we should be aiming for code that is so beautiful and simple that it doesn't require commenting; comments should be left for exceptional circumstances in which something really can't be clearly expressed in the code. But that's definitely separate from documentation which should be separate, and at a much higher level.
- notacoward 12y agoMostly good advice, sometimes even great, but the part about typedefs is total BS. Any non-trivial program will use values that have clearly different meanings but end up being the same C integer type. One's an index, one's a length, one's a repeat count, one's an enumerated value ("enum" was added to the language to support this very usage), and so on. It's stupid that C compilers don't distinguish between any two types that are the same width and signedness; why compound that stupidity? Both humans and static analyzers could tell the difference if you used typedefs, and avoid quite a few bugs as a result. Being able to change one type easily might also make some future maintainer's life much better. There's practically no downside except for having to look up the type in some situations (to see what printf format specifier to use), but that's a trivial problem compared to those that can result from not using a typedef. Don't want to use typedefs? I think that's a missed opportunity, but OK. Don't use them. OTOH, anyone who tries to pretend that the bad outweighs the good, or discourage others from using them, is an ass. Such advice for the kernel is even hypocritical, when that code uses size_t and off_t and many others quite liberally.
- bluecalm 12y agoAs a recreational C programmer I have the same impression. I've always used typedefs for structs and enums in my code and I think it makes it more readable and easier to work on. My reaction to reading the kernel style guidelines was a surprise and I am happy I am not the only one disagreeing.
- coldpie 12y agoAs a "professional" C/C++ programmer (day job), I don't have strong feelings either way. It is frustrating not knowing what the type of a variable is. Am I being passed a pointer, or an integer, or a floating point value, or a whole struct, or what? This really matters! Digging up the definition isn't difficult, but isn't easy, either. I would lean against using typedefs liberally, but I don't feel strongly about it. Personally I use typedefs as a shortcut. Rather than type boost::shared_ptr<const MyFavoriteClass> over and over, typedef it to ConstMyFavoriteClassPtr for convenience. Then be consistent with that paradigm through the whole project, so you only have to learn it once to know any given Ptr type.
- jackalope 12y ago"Get a decent editor and don't leave whitespace at the end of lines." Trailing whitespace always raises a huge red flag for me whenever I look at someone's code. It's not just sloppy, it often makes diff output so noisy you can't detect real changes to the code.
- teacup50 12y agoWho cares? Get a decent editor that doesn't give a crap if there's invisible whitespace at the end of a line.
- uniformlyrandom 12y agoor run perl -e s/(.*)\s+$/$1/g
- edran 12y agoAs the top commenter said, the problems do not end with choosing a good editor and fixing its display methodology. Git and many other VCSs create noisy diffs whenever space is added and forgotten, which ultimately complicates the life of developers that want to review changes. Even if your editor were able to make display diffs in a clean way, you would still have a dirty history when for instance using less/more or other tools (not to mention the merging issues problem).
- teacup50 12y ago> Git and many other VCSs create noisy diffs whenever space is added and forgotten, which ultimately complicates the life of developers that want to review changes. That's because Git is stupidly opinionated about end-of-line whitespace, having been written by .... Linus.
- pshc 12y agoRight, but that's only half of the robustness principle.
- Perseids 12y agoI understand that it would be bad to introduce whitespace-only changes, but why would whitespace at the end of the line that doesn't break the 80 character limit be a problem otherwise? Sure, git colors them red in its diffs, but that is kind of a circular reasoning. E.g. in this diff 0a1 > k=2 2c3,4 < print(i) --- > k*=k > print(k) you don't even see the spaces after "k=2" and "k*=k".
- thatswrong0 12y ago> Do not unnecessarily use braces where a single statement will do. if (condition) action(); > and if (condition) do_this(); else do_that(); The Apple SSL bug (https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/ https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-got...) makes me wonder if this is really worth the potential for introducing bugs.
- DSMan195276 12y agoIMO, the bug was a much deeper issue then simply not putting braces on if statements. It doesn't matter if the code becomes this: if (condition) { goto fail; } goto fail; if nobody looks at the commit. Don't get me wrong though, braces on if's do help for making cleaner patches, so there is a valid reason to request braces. You should never rely on them to fix these types of bugs though, that's bound to come back and bite you. In general, having a proper system for submitting and approving patches (Like the Kernel has) will allow you to avoid errors like this one.
- thatswrong0 12y agoI certainly don't disagree with you on the importance of process. I was going to mention how this probably would never be an issue for the kernel. To me, though, requiring braces would make it much easier to spot any such problem at any point in the development process (writing, debugging, reviewing, maintenance) such that the extra line per conditional would be well worth it in all cases, not to mention making edits easier.
- DSMan195276 12y agoI think it's worth noting that a pretty big percentage of the if's in the kernel are one line. I'm not particularly tied to one opinion or the other, I'll do whatever fits with the project (Though I do tend to use the one line if syntax for personal projects). But, I personally like them in the kernel's source simply because one line if's are so common and mostly encouraged. IMO, a better solution is to use a context-aware patch system, rather then line-based patches. That brings it's own set of problems though unfortunately. That said, I think the argument does apply in that some pieces of the kernel don't strictly follow the kernel style, and the fact that braces aren't enforced leads to some uglier pieces of code [0] being allowed despite not strictly adhering to the style. [0] https://github.com/torvalds/linux/blob/master/kernel/groups.c#L30 https://github.com/torvalds/linux/blob/master/kernel/groups....
- BugsBunnySan 12y agoIt's a very nice coding style. It keeps the code in pieces that are easy to grasp as units, it doesn't waste space and doesn't clutter the code at the same time. Just take any random function from the kernel sources and ask yourself, what does it do. I think in most cases you'll find it's really obvious... For me I find the kernel sources one of the most readable and understandable sources I've seen. The structure of them is just so clearly visible from the sources. I think a lot of that has to do with the coding style.
- geekam 12y ago>> Do not unnecessarily use braces where a single statement will do. Shouldn't this be changed to always use braces? Given the Apple bug?
- dllthomas 12y agoThe "Apple bug" - I assume you mean the duplicated "goto fail" - isn't really a common kind of error. That said, there are others that "braces everywhere" does protect from somewhat. The question is whether the clutter trades off too much in readability. Linus apparently thinks it does.
- Nmachine 12y agoI stopped reading pretty early on: ... if you need more than three levels of indentation you're screwed and should rewrite...
- whoisthemachine 12y agoI agree with and already practice many of these conventions (at least the ones that apply to C-like languages in general). It's interesting that I do and I kind of wonder what lead me down that path, since I haven't programmed in C since my college days. I often think that my assembly class from those days pushed me into making my code as vertical as possible rather than the indented-if-statement-curly-brace hell that I often see, since assembly was very readable without having that capability.