Federico Mena-Quintero
federico@gnome.org 2013
GTK+-gruppen
Våra riktlinjer för C-kod i GNOME
Anders Jonsson
anders.jonsson@norsjovallen.se 2018

# C-kodstil

Detta dokument presenterar den föredragna kodstilen för C-program i GNOME. Medan kodstil väldigt mycket är en fråga om smak så föredrar vi i GNOME en kodstil som främjar konsekvens, läsbarhet och lätthet att underhålla.

Vi presenterar exempel på bra kodstil så väl som exempel på dålig stil som inte är acceptabel i GNOME. Försök att skicka in patchar som följer GNOME:s kodstil, detta antyder att du gjort din läxa att respektera projektets mål av underhållbarhet i det långa loppet. Patchar med GNOME:s kodstil kommer också vara lättare att granska!

Detta dokument är för C-kod. För andra språk, se huvudsidan för programmeringsriktlinjerna för GNOME.

These guidelines are heavily inspired by GTK’s CODING-STYLE document, the Linux Kernel’s CodingStyle, and the GNU Coding Standards. These are slight variations of each other, with particular modifications for each project’s particular needs and culture, and GNOME’s version is no different.

# Den absolut viktigaste regeln

Den absolut viktigaste regeln vid skrivning av kod är detta: titta på omgivande kod och försök imitera den.

As a maintainer it is dismaying to receive a patch that is obviously in a different coding style to the surrounding code. This is disrespectful, like someone tromping into a spotlessly-clean house with muddy shoes.

Så, vad än detta dokument rekommenderar, om det redan finns skriven kod som du patchar, behåll dess aktuella stil konsekvent även om det inte är din favoritstil.

# Radbredd

Försök att använda kodrader från 80 till 120 tecken långa. Denna textmängd passar lätt på de flesta skärmar med en rimlig typsnittsstorlek. Längre rader än så blir svåra att läsa, och betyder att du troligen bör strukturera om din kod. Om du har för många indenteringsnivåer betyder det i vilket fall att du borde fixa till din kod.

# Indentering

Allmänt finns det två föredragna indenteringsstilar för kod i GNOME.

Linux Kernel style. Tabs with a length of 8 characters are used for the indentation, with K&R brace placement:

for (i = 0; i < num_elements; i++) { foo[i] = foo[i] + 42;

if (foo[i] < 35) { printf ("Foo!"); foo[i]--; } else { printf ("Bar!"); foo[i]++; } }

GNU style. Each new level is indented by 2 spaces, braces go on a line by themselves, and they are indented as well.

for (i = 0; i < num_elements; i++) { foo[i] = foo[i] + 42;

if (foo[i] < 35) { printf ("Foo!"); foo[i]--; } else { printf ("Bar!"); foo[i]++; } }

Båda stilarna har sina för- och nackdelar. Det viktigaste är att vara konsekvent med omgivande kod. Exempelvis så är GTK+-biblioteket, GNOME:s komponentverktygslåda, skriven med GNU-stilen. Nautilus, GNOME:s filhanterare, är skriven i Linux-kärnans stil. Båda stilarna är fullständigt läsbara och konsekventa då du vant dig med dem.

Your first feeling when having to study or work on a piece of code that doesn’t have your preferred indentation style may be, how shall we put it, gut-wrenching. You should resist your inclination to reindent everything, or to use an inconsistent style for your patch. Remember the first rule: be consistent and respectful of that code’s customs, and your patches will have a much higher chance of being accepted without a lot of arguing about the right indentation style.

# Tabbtecken

Do not ever change the size of tabs in your editor; leave them as 8 spaces. Changing the size of tabs means that code that you didn’t write yourself will be perpetually misaligned.

Instead, set the indentation size as appropriate for the code you are editing. When writing in something other than Linux kernel style, you may even want to tell your editor to automatically convert all tabs to 8 spaces, so that there is no ambiguity about the intended amount of space.

# Braces

Curly braces should not be used for single statement blocks:

/* giltig */ if (condition) single_statement (); else another_single_statement (arg1);

The “no block for single statements” rule has only four exceptions:

In GNU style, if either side of an if-else statement has braces, both sides should, to match up indentation:

/* giltig GNU-stil */ if (condition) { foo (); bar (); } else { baz (); }
/* ogiltig */ if (condition) { foo (); bar (); } else baz ();

If the single statement covers multiple lines, e.g. for functions with many arguments, and it is followed by `else` or `else if`:

/* giltig stil för Linux-kärnan */ if (condition) { a_single_statement_with_many_arguments (some_lengthy_argument, another_lengthy_argument, and_another_one, plus_one); } else another_single_statement (arg1, arg2);

/* giltig GNU-stil */ if (condition) { a_single_statement_with_many_arguments (some_lengthy_argument, another_lengthy_argument, and_another_one, plus_one); } else { another_single_statement (arg1, arg2); }

If the condition is composed of many lines:

/* giltig stil för Linux-kärnan */ if (condition1 || (condition2 && condition3) || condition4 || (condition5 && (condition6 || condition7))) { a_single_statement (); }

/* giltig GNU-stil */ if (condition1 || (condition2 && condition3) || condition4 || (condition5 && (condition6 || condition7))) { a_single_statement (); }

Note that such long conditions are usually hard to understand. A good practice is to set the condition to a boolean variable, with a good name for that variable. Another way is to move the long condition to a function.

Nested `if`s, in which case the block should be placed on the outermost `if`:

/* giltig stil för Linux-kärnan */ if (condition) { if (another_condition) single_statement (); else another_single_statement (); }

/* giltig GNU-stil */ if (condition) { if (another_condition) single_statement (); else another_single_statement (); }
/* ogiltig */ if (condition) if (another_condition) single_statement (); else if (yet_another_condition) another_single_statement ();

In general, new blocks should be placed on a new indentation level, like this:

int retval = 0;

statement_1 (); statement_2 ();

{ int var1 = 42; gboolean res = FALSE;

res = statement_3 (var1);

retval = res ? -1 : 1; }

While curly braces for function definitions should rest on a new line they should not add an indentation level:

/* giltig stil för Linux-kärnan*/ static void my_function (int argument) { do_my_things (); }

/* giltig GNU-stil*/ static void my_function (int argument) { do_my_things (); }
/* ogiltig */ static void my_function (int argument) { do_my_things (); }

/* ogiltig */ static void my_function (int argument) { do_my_things (); }

# Villkor

Do not check boolean values for equality. By using implicit comparisons, the resulting code can be read more like conversational English. Another rationale is that a ‘true’ value may not be necessarily equal to whatever the `TRUE` macro uses. For example:

/* ogiltig */ if (found == TRUE) do_foo ();

/* ogiltig */ if (found == FALSE) do_bar ();
/* giltig */ if (found) do_foo ();

/* giltig */ if (!found) do_bar ();

The C language uses the value 0 for many purposes. As a numeric value, the end of a string, a null pointer and the `FALSE` boolean. To make the code clearer, you should write code that highlights the specific way 0 is used. So when reading a comparison, it is possible to know the variable type. For boolean variables, an implicit comparison is appropriate because it’s already a logical expression. Other variable types are not logical expressions by themselves, so an explicit comparison is better:

/* giltig */ if (some_pointer == NULL) do_blah ();

/* giltig */ if (number == 0) do_foo ();

/* giltig */ if (str != NULL && *str != '\0') do_bar ();
/* ogiltig */ if (!some_pointer) do_blah ();

/* ogiltig */ if (!number) do_foo ();

/* ogiltig */ if (str && *str) do_bar ();

# Funktioner

Funktioner bör deklareras genom att placera det returnerade värdet på en separat rad från funktionsnamnet:

void my_function (void) { … }

The argument list must be broken into a new line for each argument, with the argument names right aligned, taking into account pointers:

void my_function (some_type_t type, another_type_t *a_pointer, double_ptr_t **double_pointer, final_type_t another_type) { … }

If you use Emacs, you can use `M-x align` to do this kind of alignment automatically. Just put the point and mark around the function’s prototype, and invoke that command.

The alignment also holds when invoking a function without breaking the line length limit:

align_function_arguments (first_argument, second_argument, third_argument);

# Whitespace

Placera alltid ett blanksteg före en inledande parentes men aldrig efter:

/* giltig */ if (condition) do_my_things ();

/* giltig */ switch (condition) { }
/* ogiltig */ if(condition) do_my_things();

/* ogiltig */ if ( condition ) do_my_things ( );

Vid deklaration av en strukturtyp, använd nya rader för att separera logiska avsnitt av strukturen:

struct _GtkWrapBoxPrivate { GtkOrientation orientation; GtkWrapAllocationMode mode;

GtkWrapBoxSpreading horizontal_spreading; GtkWrapBoxSpreading vertical_spreading;

guint16 vertical_spacing; guint16 horizontal_spacing;

guint16 minimum_line_children; guint16 natural_line_children;

GList *children; };

Ta inte bort blanksteg och nyrader bara för att något skulle rymmas på en enda rad:

/* ogiltig */ if (condition) foo (); else bar ();

Eliminera efterföljande blanksteg på alla rader, förslagsvis som en separat patch eller incheckning. Använd aldrig tomma rader i början eller i slutet på en fil.

Det här är en liten Emacs-funktion som du kan använda för att rensa rader med efterföljande blanksteg:

(defun clean-line-ends () (interactive) (if (not buffer-read-only) (save-excursion (goto-char (point-min)) (let ((count 0)) (while (re-search-forward "[ ]+$" nil t) (setq count (+ count 1)) (replace-match "" t t)) (message "Rensade %d rader" count)))))

# `switch`-satsen

A `switch` should open a block on a new indentation level, and each `case` should start on the same indentation level as the curly braces, with the case block on a new indentation level:

/* giltig stil för Linux-kärnan */ switch (condition) { case FOO: do_foo (); break;

case BAR: do_bar (); break; }

/* giltig GNU-stil */ switch (condition) { case FOO: do_foo (); break;

case BAR: do_bar (); break; }
/* ogiltig */ switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; }

/* ogiltig */ switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; }

/* ogiltig */ switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; }

Det är önskvärt, men inte obligatoriskt, att separera de olika case-alternativen med en nyrad:

switch (condition) { case FOO: do_foo (); break;

case BAR: do_bar (); break;

default: do_default (); }

`break`-satsen för `default`-fallet är inte obligatorisk.

If switching over an enumerated type, a `case` statement must exist for every member of the enumerated type. For members you do not want to handle, alias their `case` statements to `default`:

switch (enumerated_condition) { case HANDLED_1: do_foo (); break;

case HANDLED_2: do_bar (); break;

case IGNORED_1: case IGNORED_2: default: do_default (); }

If most members of the enumerated type should not be handled, consider using an `if` statement instead of a `switch`.

If a `case` block needs to declare new variables, the same rules as the inner blocks apply (see above); the `break` statement should be placed outside of the inner block:

/* giltig GNU-stil */ switch (condition) { case FOO: { int foo;

foo = do_foo (); } break;

… }

# Header-filer

Den enda stora regeln för header-filer är att funktionsdefinitionerna bör vara vertikalt justerade i tre kolumner:

return_type function_name (type argument, type argument, type argument);

Den maximala bredden för varje kolumn ges av det längsta elementet i kolumnen:

void gtk_type_set_property (GtkType *type, const gchar *value, GError **error); const gchar *gtk_type_get_property (GtkType *type);

Det är också möjligt att justera kolumnerna till nästa tabb:

void gtk_type_set_prop (GtkType *type, gfloat value); gfloat gtk_type_get_prop (GtkType *type); gint gtk_type_update_foobar (GtkType *type);

Som tidigare kan du använda `M-x align` i Emacs för att göra detta automatiskt.

If you are creating a public library, try to export a single public header file that in turn includes all the smaller header files into it. This is so that public headers are never included directly; rather a single include is used in applications. For example, GTK+ uses the following in its header files that should not be included directly by applications:

#if !defined (__GTK_H_INSIDE__) && !defined (GTK_COMPILATION) #error "Only <gtk/gtk.h> can be included directly." #endif

For libraries, all headers should have inclusion guards (for internal usage) and C++ guards. These provide the `extern "C"` magic that C++ requires to include plain C headers:

#ifndef MYLIB_FOO_H_ #define MYLIB_FOO_H_

#include <gtk/gtk.h>

G_BEGIN_DECLS

…

G_END_DECLS

#endif /* MYLIB_FOO_H_ */

# GObject-klasser

GObject class definitions and implementations require some additional coding style notices, and should always be correctly namespaced.

Typedef declarations should be placed at the beginning of the file:

typedef struct _GtkBoxedStruct GtkBoxedStruct; typedef struct _GtkMoreBoxedStruct GtkMoreBoxedStruct;

This includes enumeration types:

typedef enum { GTK_SIZE_REQUEST_WIDTH_FOR_HEIGHT, GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH } GtkSizeRequestMode;

And callback types:

typedef void (* GtkCallback) (GtkWidget *widget, gpointer user_data);

Instance structures should be declared using `G_DECLARE_FINAL_TYPE` or `G_DECLARE_DERIVABLE_TYPE`:

#define GTK_TYPE_FOO (gtk_foo_get_type ()) G_DECLARE_FINAL_TYPE (GtkFoo, gtk_foo, GTK, FOO, GtkWidget)

For final types, private data can be stored in the object struct, which should be defined in the C file:

struct _GtkFoo { GObject parent_instance;

guint private_data; gpointer more_private_data; };

For derivable types, private data must be stored in a private struct in the C file, configured using `G_DEFINE_TYPE_WITH_PRIVATE()` and accessed using a `_get_instance_private()` function:

#define GTK_TYPE_FOO gtk_foo_get_type () G_DECLARE_DERIVABLE_TYPE (GtkFoo, gtk_foo, GTK, FOO, GtkWidget)

struct _GtkFooClass { GtkWidgetClass parent_class;

void (* handle_frob) (GtkFrobber *frobber, guint n_frobs);

gpointer padding[12]; };

Always use the `G_DEFINE_TYPE()`, `G_DEFINE_TYPE_WITH_PRIVATE()`, and `G_DEFINE_TYPE_WITH_CODE()` macros, or their abstract variants `G_DEFINE_ABSTRACT_TYPE()`, `G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE()`, and `G_DEFINE_ABSTRACT_TYPE_WITH_CODE()`; also, use the similar macros for defining interfaces and boxed types.

Interface types should always have the dummy typedef for cast purposes:

typedef struct _GtkFooable GtkFooable;

The interface structure should have ‘Interface’ postfixed to the dummy typedef:

typedef struct _GtkFooableInterface GtkFooableInterface;

Gränssnitt måste ha följande makron:

Makro | Expanderas till
--- | ---
`GTK_TYPE_iface_name` | `iface_name_get_type`
`GTK_iface_name` | `G_TYPE_CHECK_INSTANCE_CAST`
`GTK_IS_iface_name` | `G_TYPE_CHECK_INSTANCE_TYPE`
`GTK_iface_name_GET_IFACE` | `G_TYPE_INSTANCE_GET_INTERFACE`

# Minnesallokering

When dynamically allocating data on the heap use `g_new()`.

Public structure types should always be returned after being zero-ed, either explicitly for each member, or by using `g_new0()`.

Se för mer detaljer.

# Makron

Try to avoid private macros unless strictly necessary. Remember to `#undef` them at the end of a block or a series of functions needing them.

Inline functions are usually preferable to private macros.

Public macros should not be used unless they evaluate to a constant.

# Öppet API

Avoid exporting variables as public API, since this is cumbersome on some platforms. It is always preferable to add getters and setters instead. Also, beware global variables in general.

# Privat API

Non-exported functions that are needed in more than one source file should be prefixed with an underscore (‘_’), and declared in a private header file. For example, `_mylib_internal_foo()`.

Funktioner som inleds med understreck exporteras aldrig.

Ej exporterade funktioner som bara behövs i en källkodsfil bör deklareras static.