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!
This document is for C code. For other languages, check the main page of the Gnome Programming Guidelines.
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.
The single most important rule when writing code is this: check the surrounding code and try to imitate it.
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.
So, whatever this document recommends, if there is already written code and you are patching it, keep its current style consistent even if it is not your favorite style.
Try to use lines of code between 80 and 120 characters long. This amount of text is easy to fit in most monitors with a decent font size. Lines longer than that become hard to read, and they mean that you should probably restructure your code. If you have too many levels of indentation, it means that you should fix your code anyway.
In general there are two preferred indentation styles for code in Gnome.
Linux Kernel style. This is 8-space indentations, 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]++;
}
}Both styles have their pros and cons. The most important things is to be consistent with the surrounding code. For example, the GTK+ library, which is Gnome's widget toolkit, is written with the GNU style. Nautilus, Gnome's file manager, is written in Linux kernel style. Both styles are perfectly readable and consistent when you get used to them.
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.
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. You may even be able to tell your editor to automatically convert all tabs to 8 spaces, so that there is no ambiguity about the intended amount of space.
Curly braces should not be used for single statement blocks:
/* valid */
if (condition)
single_statement ();
else
another_single_statement (arg1);The "no block for single statements" rule has only four exceptions:
If the single statement covers multiple lines, e.g. for functions with many arguments, and it is followed by else or else if:
/* 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);If the condition is composed of many lines:
/* 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 ();
}Nested if's, in which case the block should be placed on the outermost if:
/* 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 ();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 ();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:
/* 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 ();
}
Do not check boolean values for equality. The rationale is that a "true" value may not be necessarily equal to whatever the TRUE macro uses. For example:
/* invalid */
if (condition == TRUE)
do_foo ();
/* valid */
if (another_condition)
do_bar ();Even if C handles NULL equality like a boolean, be explicit. This makes it easier to port your C code to something like C#, where testing against null explicitly is important:
/* valid */
if (some_pointer == NULL)
do_blah ();
/* valid */
if (something != NULL)
do_foo ();
/* invalid */
if (some_other_pointer)
do_blurp ();Functions should be declared by placing the returned value on a separate line from the function name:
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);
Always put a space before an opening parenthesis but never after:
/* valid */
if (condition)
do_my_things ();
/* valid */
switch (condition) {
}
/* invalid */
if(condition)
do_my_things();
/* invalid */
if ( condition )
do_my_things ( );
When declaring a structure type use newlines to separate logical sections of the structure:
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;
};
Do not eliminate whitespace and newlines just because something would fit on a single line:
/* invalid */
if (condition) foo (); else bar ();
Do eliminate trailing whitespace on any line, preferably as a separate patch or commit. Never use empty lines at the beginning or at the end of a file.
This is a little Emacs function that you can use to clean up lines with trailing whitespace:
(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)))))
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:
/* 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;
}
It is preferable, though not mandatory, to separate the various cases with a newline:
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 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;
...
}
The only major rule for headers is that the function definitions should be vertically aligned in three columns:
return value function_name (type argument,
type argument,
type argument);
The maximum width of each column is given by the longest element in the column:
void gtk_type_set_property (GtkType *type,
const gchar *value,
GError **error);
const gchar *gtk_type_get_property (GtkType *type);
It is also possible to align the columns to the next tab:
void gtk_type_set_prop (GtkType *type,
gfloat value);
gfloat gtk_type_get_prop (GtkType *type);
gint gtk_type_update_foobar (GtkType *type);
As before, you can use M-x align in Emacs to do this automatically.
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 class definitions and implementations require some additional coding style notices.
Typedef declarations should be placed at the beginning of the file:
typedef struct _GtkFoo GtkFoo;
typedef struct _GtkFooClass GtkFooClass;
typedef struct _GtkFooPrivate GtkFooPrivate;
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 only contain the parent type, and optionally a pointer to a private data structure, and they should be annotated as "private" using the gtk-doc trigraph:
struct _GtkFoo
{
/*< private >*/
GtkWidget parent_instance;
GtkFooPrivate *priv;
};
The private data pointer is optional and should be omitted in newly written classes.
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.
All the properties should be stored inside the private data structure, which is defined inside the source file - or, if needed, inside a private header file; the private header filename must end with "private.h" and must not be installed.
The private data structure should only be accessed internally either using the pointer inside the instance structure, if one is available, or the generated instance private data getter function for your type. You should never use the G_TYPE_INSTANCE_GET_PRIVATE() macro or the g_type_instance_get_private() function.
Interface types should always have the dummy typedef for cast purposes:
typedef struct _GtkFoo GtkFoo;
The interface structure should have "Interface" postfixed to the dummy typedef:
typedef struct _GtkFooInterface GtkFooInterface;
Interfaces must have the following macros:
Macro |
Expands to |
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 |
When dynamically allocating data on the heap either use g_new() or, if allocating multiple small data structures, g_slice_new().
Public structure types should always be returned after being zero-ed, either explicitly for each member, or by using g_new0() or g_slice_new0().
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.
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.
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().
Underscore-prefixed functions are never exported.
Non-exported functions that are only needed in one source file should be declared static.
The preferred documentation system for GNOME libraries is gtk-doc, which extracts inline comments from the code to let you build a DocBook document. A lot of GNOME's infrastructure is built to handle with documentation written using gtk-doc.
All public APIs must have gtk-doc comments. For functions, these should be placed in the source file, directly above the function.
/* valid */
/**
* gtk_get_flow:
* @widget: a #GtkWidget
*
* Gets the flow of a widget.
*
* Note that flows may be laminar or turbulent...
*
* Returns: (transfer none): the flow of @widget
*/
GtkFlow *
gtk_get_flow (GtkWidget *widget)
{
...
}
Documentation comments for macros, function types, class structs, etc. should be placed next to the definitions, typically in header files.
Section introductions should be placed in the source file they describe, after the license header:
/* valid */
/**
* SECTION:gtksizerequest
* @Short_Description: Height-for-width geometry management
* @Title: GtkSizeRequest
*
* The GtkSizeRequest interface is GTK+'s height-for-width (and
* width-for-height) geometry management system.
* ...
*/
Keep in mind that in order to include a function, macro, function type, or struct type, it needs to be listed in your documentation's modulename-sections.txt file.
To properly document a new class, it needs to be given its own section in modulename-sections.txt, needs to be included in your toplevel modulename-docs.sgml, and the get_type() function for your class needs to listed in your modulename.types.
Got a comment? Spotted an error? Found the instructions unclear? Send feedback about this page.