User:Love4Boobies/C style guide

From OSDev Wiki
Jump to: navigation, search

Please adhere to this style guide when adding C/C++ code to the Wiki.


Overall Style

// Make "takes no parameters" explicit by using "void".
int defined_elsewhere( void );
// Describe the purpose of the function, of the parameters it takes,
// and its return value (if any). Reference any third-party sources
// or algorithms used. Document specific design decisions.
void * foobar( int a, int * b )
    int c;
    // Summarize purpose of code blocks.
    if ( a == *b )
        puts( "The values are equal." );
        puts( "The values are different; clearing a." );
        a = 0;
    // Summarize purpose of code blocks.
    while ( ( c = getchar() ) != EOF )
        switch ( c )
            case '0':
                *b = a;
            case '1':
                *b = a / 2;
                *b = 0;
    // see "Operator sizeof" below.
    return malloc( sizeof( *b ) );

Note: If you don't feel like formatting your code to the standards above manually, you could use one of several available code reformatters:

  • astyle -A1 -p -D -f -S -xd -k2
  • ...

Standard library

The following headers are available in freestanding implementations. Please do not duplicate in custom typedefs etc. what these headers define in a portable, standard way:

* <float.h>
* <iso646.h>
* <limits.h>
* <stdalign.h>
* <stdarg.h>
* <stdbool.h>
* <stddef.h>
* <stdint.h>

Consider using the interface defined by <iohw.h> (TR 18037) for accessing ports, too. (Instead of using functions such as inb and outb.)

Typedef names

Avoid typedef's. They will not save you much typing in the scope of this Wiki.

Operator sizeof

Using sizeof on object name instead of type remains correct even if type is changed. Even while sizeof is an operator, not a function, writing it like a function usually helps readability. Just remember you cannot take its address, that its operand is not evaluated, and that you don't need to cache sizes as this is a compile-time construct.

Compiler-specific extensions

Avoid them unless they are the subject of the article (i.e., Inline Assembly). In particular, things like GCC's __attribute__ ((aligned (16), packed)) should be substituted with proper serialization (e.g., arrays, or files), and language alignment support (as introduced in C1X) --- if not, at least use unions to force alignment.

The compiler is your friend

Your code should compile with:

  • gcc -std=c99 -Winit-self -Wfloat-equal -Wundef -pedantic -Wall -Wextra -Werror
  • g++ -pedantic -Wall -Wextra -Werror
Personal tools