Coding Style
In general, the coding standards used in the Linux kernel are versatile, comprehensive and quite good looking. They are boiling down to the following guide lines:
- Indentation
- Four spaces
- Spaces
- Spaces around keywords but not in inner parenthesis.
- Brace placement
- '{' at end of line except for function definition and '}' on its own line except in do-while-loops.
- Naming
- Descriptive for global functions and usually lower case with underscores.
- Macros
- Upper case for constants, lower case with underscores for macros resembling functions.
- Structures
- Consistency when using typedefs or not. For shared data structures reference counting should be implemented.
I would add the following:
- Position of C-pointer star
- At variable name not type.
- const
- Wherever possible.
- White space
- Avoid at all costs.
- C99
- Enable it and declare variables only when needed.
There are still some open questions:
- Number of newlines to separate functions?
- Comments: C vs. C++ style, usage of '*'?
- Alignment of multiple assignments?
- Breaking of long lines, especially argument lists?
- #define indentation? Commenting each #endif with the corresponding #define name makes the code hard to read in my opinion.
- Documentation tools? (Doxygen, Sphinx, Natural Docs)
- Name prefixes? (e.g. 'g_' for global)
In essence, a bit of code would look like that:
#define PI 3.14159265 #define min(a,b) ((a) < (b) ? (a) : (b)) struct string { char *content; size_t length; int refcount; }; struct string* clone_string(const char *s) { if (s == NULL) return NULL; struct string *clone = (struct string *) malloc(sizeof(struct string)); const int len = strlen(s); clone->content = (char *) malloc(len); clone->length = len; clone->refcount = 1; strncpy(clone->content, s, len); return clone; }
Astyle Formatter
Corresponding flags for the astyle formatter are
astyle --style=k/r --indent=spaces --indent-switches --break-blocks --pad-oper --pad-header --delete-empty-lines --break-closing-brackets --align-pointer=name filename.c
Last modified 13 years ago
Last modified on Dec 16, 2011, 2:36:11 PM