Federico Mena-Quintero federico@gnome.org 2013 Das GTK+-Team Unsere Richtlinien für C-Code in GNOME Mario Blättermann mario.blaettermann@gmail.com 2016 Christian Kirbach christian.kirbach@gmail.com 2016 C-Programmierstil

This document presents the preferred coding style for C programs in GNOME. While coding style is very much a matter of taste, in GNOME we favor a coding style that promotes consistency, readability, and maintainability.

We present examples of good coding style as well as examples of bad style that is not acceptable in GNOME. Please try to submit patches that conform to GNOME’s coding style; this indicates that you have done your homework to respect the project’s goal of long-term maintainability. Patches with GNOME’s coding style will also be easier to review!

Dieses Dokument bezieht sich auf C-Programmcode. Informationen zu anderen Sprachen finden Sie auf der Hauptseite der GNOME-Programmierrichtlinien.

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.

Die allerwichtigste Regel

Die allerwichtigste Regel für das Schreiben von Code ist: Schauen Sie sich den umgebenden Code an und versuchen Sie, dessen Stil zu imitieren.

Für einen Maintainer ist es erschreckend, einen Patch zu bekommen, der vom umgebenden Code stilistisch stark abweicht. Das ist respektlos, so als jemand mit schlammigen Schuhen in ein blitzsauberes Haus hineintrampelt.

Was auch immer dieses Dokument empfiehlt, so sollte sich Ihr Stil stets am Stil des bereits vorhandenen Codes orientieren, auch wenn es nicht Ihr bevorzugter Stil ist.

Zeilenbreite

Versuchen Sie, Ihre Zeilen zwischen 80 und 120 Zeichen breit zu halten. Diese Breite passt am besten in die meisten Bildschirme mit einer vernünftigen Schriftgröße. Längere Zeilen sind schwerer zu lesen, außerdem sollten Sie sich in diesem Fall überlegen, ob Sie Ihren Code nicht anders beziehungsweise besser strukturieren sollten. Bei zu vielen Einrückungsebenen sollte Ihr Code ohnehin überarbeitet werden.

Einzüge

Allgemein gibt es zwei zu bevorzugende Einzugsstile für Code in GNOME.

Linux-Kernel-Stil. Tabulatoren für Einrückungen sind 8 Zeichen breit, mit einer K&R-Klammernplatzierung:

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-Stil. Jede neue Ebene wird um zwei Leerzeichen eingerückt, Klammern werden in eine eigene Zeile gesetzt und ebenfalls eingerückt.

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]++; } }

Beide Stile haben ihre Befürworter und Gegner. Der wichtigste Punkt ist die Konsistenz zum umgebenden Code. Zum Beispiel ist die GTK+-Bibliothek als Widget-Toolkit für GNOME im GNU-Stil geschrieben. Nautilus dagegen, der Dateimanager von GNOME, folgt dem Linux-Kernel-Stil. Beide Stile sind bestens lesbar und konsistent, wenn Sie sie verwenden.

Ihr erstes Gefühl bei der Arbeit an Programmcode, der nicht Ihrem bevorzugten Einrückungsstil folgt, könnte, sagen wir, ablehnend sein. Widerstehen Sie dem Drang, alles neu einrücken zu wollen, oder für Ihren Patch einen inkonsistenten Stil zu verwenden. Erinnern Sie sich an die oberste Regel: Konsistenz und Respekt vor den Eigenheiten des fremden Codes, und Ihre Patches haben eine ungleich größere Chance, ohne langatmige Diskussionen über den richtigen Einrückungsstil angenommen zu werden.

Tabulatorzeichen

Ändern Sie niemals die Tabulatorbreite in Ihrem Editor. Behalten Sie 8 Zeichen bei. Durch Änderungen der Tabulatorbreite wird Code, den Sie nicht selbst geschrieben haben, immer falsch ausgerichtet.

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.

Klammern

Geschweifte Klammern sollten nicht für einzelne Anweisungsblöcke verwendet werden:

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

Für die Regel »kein Block für einzelne Anweisungen« gibt es vier Ausnahmen:

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

/* valid GNU style */ if (condition) { foo (); bar (); } else { baz (); } /* invalid */ if (condition) { foo (); bar (); } else baz ();

Wenn sich die einzelne Anweisung über mehrere Zeilen erstreckt, zum Beispiel für Funktionen mit vielen Argumenten, und wenn darauf else oder else if folgt:

/* valid Linux kernel style */ 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); /* valid GNU style */ 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); }

Wenn die Bedingung aus mehreren Zeilen besteht:

/* valid Linux kernel style */ if (condition1 || (condition2 && condition3) || condition4 || (condition5 && (condition6 || condition7))) { a_single_statement (); } /* valid GNU style */ if (condition1 || (condition2 && condition3) || condition4 || (condition5 && (condition6 || condition7))) { a_single_statement (); }

Bedenken Sie, dass solche überlangen Bedingungen oft schwer verständlich sind. Eine gute Alternative wäre, die Bedingung in eine boolesche Variable zu setzen und einen passenden Namen dafür zu wählen. Eine weitere Möglichkeit ist die Auslagerung der langen Bedingung in eine Funktion.

Verschachtelte ifs, wobei der Block im äußersten if platziert werden sollte:

/* valid Linux kernel style */ if (condition) { if (another_condition) single_statement (); else another_single_statement (); } /* valid GNU style */ if (condition) { if (another_condition) single_statement (); else another_single_statement (); } /* invalid */ if (condition) if (another_condition) single_statement (); else if (yet_another_condition) another_single_statement ();

Generell sollten neue Blöcke in eine neue Einrückungsebene gesetzt werden, wie hier:

int retval = 0; statement_1 (); statement_2 (); { int var1 = 42; gboolean res = FALSE; res = statement_3 (var1); retval = res ? -1 : 1; }

Während geschweifte Klammern für Funktionsdefinitionen in eine neue Zeile gehören, sollten sie nicht weiter eingerückt werden:

/* valid Linux kernel style*/ static void my_function (int argument) { do_my_things (); } /* valid GNU style*/ static void my_function (int argument) { do_my_things (); } /* invalid */ static void my_function (int argument) { do_my_things (); } /* invalid */ static void my_function (int argument) { do_my_things (); }
Bedingungen

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:

/* invalid */ if (found == TRUE) do_foo (); /* invalid */ if (found == FALSE) do_bar (); /* valid */ if (found) do_foo (); /* valid */ if (!found) do_bar ();

Die Programmiersprache C verwendet den Wert 0 für zahlreiche Zwecke, als numerischen Wert, als Ende einer Zeichenkette, als Null-Zeiger oder für den booleschen Wert FALSE. Um hier etwas mehr Klarheit zu schaffen, sollte in Ihrem Code der Zwecke entsprechend gekennzeichnet werden. So kann bei Vergleichen der Variablentyp erkannt werden. Für boolesche Variablen ist ein impliziter Vergleich angemessen, da es bereits ein logischer Ausdruck ist. Andere Variablentypen sind nicht direkt logische Ausdrücke, so dass ein expliziter Vergleich besser erscheint:

/* valid */ if (some_pointer == NULL) do_blah (); /* valid */ if (number == 0) do_foo (); /* valid */ if (str != NULL && *str != '\0') do_bar (); /* invalid */ if (!some_pointer) do_blah (); /* invalid */ if (!number) do_foo (); /* invalid */ if (str && *str) do_bar ();
Funktionen

Funktionen sollten so deklariert werden, dass der Rückgabewert in einer separaten Zeile vom Funktionsnamen abgesetzt wird:

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);
Leerzeichen

Setzen Sie stets vor einer öffnenden Klammer ein Leerzeichen, aber niemals dahinter:

/* valid */ if (condition) do_my_things (); /* valid */ switch (condition) { } /* invalid */ if(condition) do_my_things(); /* invalid */ if ( condition ) do_my_things ( );

Bei der Deklaration eines Strukturtyps verwenden Sie einen Zeilenumbruch, um logische Abschnitte der Struktur zu trennen:

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; };

Entfernen Sie keine Leerzeichen und Zeilenumbrücke, nur weil etwas auch in eine einzelne Zeile passen würde:

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

Entfernen Sie stets angehängte Leerzeichen in jeder Zeile, vorzugsweise mittels separatem Patch oder Commit. Setzen Sie niemals leere Zeilen an den Anfang oder das Ende einer Datei.

Hier ist eine kleine Emacs-Funktion, mit der Sie Zeilen mit angehängten Leerzeichen bereinigen können:

(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 "Cleaned %d lines" count)))))
Die <code>switch</code>-Anweisung

Ein switch sollte einen Block in einer neuen Einrückungsebene öffnen, und jedes case sollte in der gleichen Einrückungsebene beginnen wie die geschweiften Klammern, mit dem case-Block in einer neuen Einrückungsebene:

/* valid Linux kernel style */ switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; } /* valid GNU style */ switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; } /* invalid */ switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; } /* invalid */ switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; } /* invalid */ switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; }

Es ist zu bevorzugen, jedoch nicht obligatorisch, die verschiedenen case durch Zeilenumbrüche voneinander zu trennen:

switch (condition) { case FOO: do_foo (); break; case BAR: do_bar (); break; default: do_default (); }

The break statement for the default case is not mandatory.

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:

/* valid GNU style */ switch (condition) { case FOO: { int foo; foo = do_foo (); } break; … }
Header-Dateien

The only major rule for headers is that the function definitions should be vertically aligned in three columns:

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

Die maximale Breite jeder Spalte wird durch das längste Element in der Spalte bestimmt:

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

Es ist auch möglich, die Spalten am nächsten Tabulator auszurichten:

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

Wie schon erwähnt, erledigt Emacs dies mit M-x align automatisch.

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-Klassen

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

Typedef-Deklarationen sollten am Anfang der Datei platziert werden:

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;

Für Schnittstellen sind die folgenden Makros zu verwenden:

Makro

Expandiert zu

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

Speicherreservierung

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().

In finden Sie weitere Details.

Makros

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.

Public 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.

Private 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().

Funktionen mit vorangestelltem Unterstrich werden niemals exportiert.

Nicht-exportierte Funktionen, die nur in einer Quelldatei benötigt werden, sollten als statisch deklariert werden.