1 ============================================================================
2 Freeciv Coding Style Guide
3 ============================================================================
5 If you want to hack Freeciv, and want your patches to be accepted, it helps
6 to follow some simple style rules. Yes, some of these are a bit nit-picky,
7 but wars are fought over the silliest things ...
9 - This style is used for all code in Freeciv. Freeciv gtk-clients use
10 this style, not gtk style.
12 - Freeciv is mostly programmed in C, C89 with some C99 features.
13 Qt parts are programmed in C++. Even C++ parts should have mostly
14 consistent style with C parts, so where not otherwise noted, this
15 guide applies to C++ parts too. Headers that are included to both
16 C and C++ source files follow C style.
18 - C++-style comments (i.e., // comments) are forbidden in C code.
19 They should be used for single-line comments in C++ code.
21 - Declaring variables in the middle of the scope is forbidden
22 (unless you are using C99 dynamic arrays and you need to check the size
23 of the array before you declare it).
25 - Where variable is logically boolean, 'bool' type should be used even in
26 C code. To make sure that the type is defined, include utility/support.h.
27 In C code boolean values are uppercase macros 'TRUE' and 'FALSE'.
28 In C++ code lowercase boolean values 'true' and 'false' should be used.
30 - Functions that take no arguments should be declared and defined with
31 'void' argument list in C code, and empty argument list in C++ code.
34 int no_arguments(void);
39 - Use K&R indentation style with indentation 2 (if in doubt, use "indent -kr
40 -i2 -l77", but beware that that will probably mangle the _() macros used
41 to mark translated strings and the brace style for iteration macros).
43 - Do not re-indent areas of code you are not modifying or creating.
45 - Here are the most important formatting rules:
47 - Lines are at most 77 characters long, including the terminating newline.
49 - The tab width is 8 spaces for tabs that already exist in the source code
50 (this is just so that old code will appear correctly in your editor).
51 However, tabs should be avoided in newly written code.
53 - The indentation is 2 spaces per level for all new code; do not use tabs
54 for any kind of indentation. The one exception to this is if you are
55 just adding one line to a set of lines that are already indented with
56 some strange mix of tabs and spaces; in this case you may use the same
57 indentation as the surrounding lines.
59 - Do not add more than 2 empty lines between any sections in the code.
61 - Spaces are inserted before and after operators: instead of "int a,b,c;"
62 use "int i, j, k;" and instead of
74 Note the space between "if" and the bracket.
76 - Switch statement case labels are aligned with the enclosing "switch":
84 int value2 = value + 5;
85 do_some_other_stuff(value2);
90 - In the rare case that you actually use goto, the label should be all
91 capitals and "out-dented" in the block in which it is contained:
93 static int frob(int n)
96 for (i = 0; i < n; i++) {
97 for (j = i; j < n; j++) {
98 if (some_condition(i, j)) {
107 - If a function prototype exceeds 77 characters on one line, you should
108 put the return value type and storage specifier on the line immediately
111 static const struct incredibly_long_structure_name *
112 get_a_const_struct_incredibly_long_structure_name(int id);
114 - If arguments in a function prototype or a function call cause the line
115 to exceed 77 characters, they should be placed on the following line and
116 lined up with spaces to the column after the '(':
118 void some_function(const struct another_really_long_name *arln,
119 int some_other_argument);
121 - If the line is still too long for some reason, you may place the
122 arguments two indentation levels on the next line:
124 a_very_awkward_long_function_name(some_argument,
125 "A really long string that would have to be cut up.");
127 But you should try to avoid this situation, either by naming your
128 functions/types/variables more succinctly, or by using helper variables
129 or functions to split the expression over a number of lines.
131 - An empty line should be placed between two separate blocks of code.
133 - Place operators at the beginning of a line, not at the end. It should be
146 ============================================================================
148 ============================================================================
150 - All comments should have proper English grammar, spelling and punctuation,
151 but you should not capitalize names of identifiers (variables, types,
152 functions, etc.) used in the code. If using plain identifiers in sentences
153 would be confusing to the reader, you should put the names in quotes.
155 - Every function should have a comment header. The comment should look like
156 the example below, indented by two spaces. It should be above the
157 function's implementation, not the prototype:
159 /****************************************************************************
160 The description of the function should be here. Also describe what is
161 expected of the arguments if it is not obvious. Especially note down any
162 non-trivial assumptions that the function makes.
164 Do _not_ introduce a new function without some sort of comment.
165 ****************************************************************************/
166 int the_function_starts_here(int value)
171 - One line comments should be indented correctly and placed above the code
172 being commented upon:
176 /* I am a single line comment. */
179 - For multiline comments, asterisks should be placed in front of the comment
186 - If you need to comment a declared variable, it should be as such:
189 int bar; /* bar is used for ...
191 int blah; /* blah is used for ... . */
194 Or if the comment is very long, it may be placed above the field
195 declaration, as in the one-line or multi-line comment cases.
197 - Comments in conditionals: if you need a comment to show program flow, it
198 should be below the if or else:
200 if (is_barbarian(pplayer)) {
203 /* If not barbarian... */
207 - Comments to translators are placed before the N_(), _(), Q_() or PL_()
208 marked string, and are preceded by "TRANS:". . They must be on the same or
209 immediately previous line to the gettext invocation. These comments are
210 copied to the translator's file. Use them whenever you think the
211 translators may need some more information:
213 /* TRANS: Do not translate "commandname". */
214 printf(_("commandname <arg> [-o <optarg>]"));
217 ============================================================================
219 ============================================================================
221 - Avoid static and global variables if at all possible. When you absolutely
222 do need them, minimize the number of times they are referenced in the code
223 (e.g. use a helper function to wrap their access).
225 - Never initialize variables with values that make no sense as their
226 value in case they get used. If there's no sensible initialization
227 value for a variable, leave it uninitialized. This allows various
228 tools to detect if such a variable ever gets used without assigning
231 - Variables can be initialized as soon as they are declared:
233 int foo(struct unit *punit)
241 (But you should generally check arguments to functions before using them,
242 unless you are absolutely sure that pointers are not NULL, etc.)
244 - After variables are declared, there should be an empty line before the
245 rest of the function body.
247 - Merging declarations: variables do not have to be declared one per line;
248 however, they should only be grouped by similar function.
250 int foo(struct city *pcity)
254 int build = pcity->shield_stock;
257 - When declaring a pointer, there should be a space before '*' and no space
258 after, except if it is a second '*'.
260 struct unit *find_random_unit(struct unit **array, size_t num)
262 struct unit *const *prand = array + fc_rand(num);
269 struct unit* find_random_unit(struct unit* *array, size_t num)
271 struct unit * const* prand = array + fc_rand(num);
277 ============================================================================
279 ============================================================================
281 - Function braces begin and end in the first column:
294 - Use extra braces for iteration macros. Note that the "*_iterate_end;"
295 should be placed on the same line as the end brace:
297 unit_list_iterate(pcity->units_supported, punit) {
299 } unit_list_iterate_end;
301 - In switch statements, braces should only be placed where needed, i.e. to
302 protect local variables.
304 - Braces shall always be used after conditionals, loops, etc.:
324 ============================================================================
326 ============================================================================
327 - First of all, reread comment about the switch statement indentations and
330 - Avoid the usage of magic values (plain hard-coded value, such as 0 or -1)
331 and prefer the usage of enumerators. If an enumeration cannot be defined
332 for any reason, then define a macro for this value.
334 - Avoid storing magic values in external processes. For example, savegames
335 shouldn't contain any enumerators as magic numbers. They should be saved
336 as strings, to keep compatibility when their definition is changed. For
337 doing this, there are some tools in utility/specenum_gen.h; have a look at
340 - Avoid the usage of the default case in switch statements, if possible. The
341 default case removes the warning of the compiler when a value is missing
342 in a switch statement.
345 ============================================================================
347 ============================================================================
348 - Order include files consistently: all includes are grouped together.
349 These groups are divided by an empty line. The order of these groups is as
352 1) fc_config.h (see below)
353 2) system include files which are OS-independent (part of C-standard or
355 3) system include files which are OS-dependent or conditional includes
356 4) include files from utility/
357 5) include files from common/
358 6) include files from client/
359 7) include files from server/ and ai/
360 8) include the header corresponding to the current c source file after
363 Each group is sorted in alphabetic order. This helps to avoid adding
364 unnecessary or duplicated include files.
366 Always set a comment to determine the location of the following headers
369 It is very important that '#include <fc_config.h>' is at the top of
370 every .c file (it need not be included from .h files). Some definitions in
371 fc_config.h will affect how the code is compiled, without which you can end
372 up with bad and untraceable memory bugs.
375 #include <fc_config.h>
386 #include "myfileheader.h"
388 - For headers within a subdirectory path, the common rule is to set them
389 in an additional group, after the same group (don't forget the location
396 #include "pf_tools.h"
398 However, there is an exception to this. The last group is always the one
399 we are working on. So, if we are working on the common part, the order
403 #include "pf_tools.h"
408 Same observations with ai/ and server/. When working on the server/
409 directory, the order should be:
415 #include "srv_main.h"
417 and working on the ai/ directory:
420 #include "srv_main.h"
425 - Do not include headers in other headers if at all possible. Use forward
426 declarations for pointers to structs:
429 void a_function(struct connection *pconn);
433 #include "connection.h"
434 void a_function(struct connection *pconn);
436 - Of course, never include headers of non-linked parts of the code. For
437 example, never include client/ headers into a server/ file. Also, in the
438 client/ directory, GUI specific headers are never included. Always, use
439 the common set of headers defined in client/include/.
442 ============================================================================
443 Object-Oriented Programming
444 ============================================================================
445 Freeciv is not really object-oriented programming, but last written parts
446 seems to tend to there. Also, there are more and more parts which are
447 modular, so there are some observations to do:
449 - Any function or member of a module must be prefixed by the name of this
450 module, or an abbreviation of it (but use the same prefix for all members
451 please!). Never set the module name as suffix!
453 /* Super mega cool module! */
454 void smc_module_init(void);
455 void smc_module_free(void);
459 /* Super mega cool module! */
460 void smc_module_init(void);
461 void sm_cool_free(void);
465 /* Super mega cool module! */
466 void init_smc_module(void);
467 void free_smc_module(void);
469 - A function which allocates memory for a pointer variable should use the
470 suffix '_new'. The memory is freed by a corresponding function with the
474 struct test *t = test_new();
479 - The suffix '_init' should be used for functions which initialize some
480 static data. The name of the corresponding function to deinitialize stuff
481 should use the suffix '_free' (see server/settings.c or common/map.c).
492 ============================================================================
494 ============================================================================
496 - If an empty statement is needed, you should put an explanatory comment
497 in an empty block (i.e. {}):
503 - Use the postfix operator instead of the prefix operator when either will
504 work. That is, write "a++" instead of "++a".
506 - Strive to make your code re-entrant (thread/recursion safe), as long as
507 this does not make the implementation too cumbersome or involved.
509 - Strive to make your code modular: make it independent from other parts of
510 the codebase, and assume as little as possible about the circumstances in
513 - Strive to avoid code duplication: if some part of the code is repeated in
514 several places, factor it out into a helper function.
516 - Try to use static inline functions and const data instead of macros.
518 - If helper functions internal to freeciv are added, prefix their names
519 with 'fc_'. Do not use 'my_' because it is also used by MySQL and could
520 be included in some libs.
522 - Do not use assert() or die(); instead use the macros defined within
526 fc_assert_ret(condition)
527 fc_assert_ret_val(condition, val)
528 fc_assert_action(condition, action_on_failure)
529 fc_assert_exit(condition, action_on_failure)
531 fc_assert_msg(condition, message, ...)
532 fc_assert_ret_msg(condition, message, ...)
533 fc_assert_ret_val_msg(condition, val, message, ...)
534 fc_assert_action_msg(condition, action_on_failure, message, ...)
535 fc_assert_exit_msg(condition, action_on_failure, message, ...)
537 This way error conditions can be handled gracefully while still enforcing
538 invariants you expect not to be violated in the code.
539 (By default execution will continue with a warning, but it can be made
540 to halt by specifying the '-F' option to the client or server.)
542 int foo_get_id(const struct foo *pfoo)
544 fc_assert_ret_val(pfoo != NULL, -1);
548 - Do not put multiple conditions in the same fc_assert*() statement:
550 fc_assert(pfoo != NULL);
551 fc_assert(pfoo->id >= 0);
555 fc_assert(pfoo != NULL && pfoo->id >= 0);
557 - Never include functionality also otherwise necessary inside fc_assert*().
558 Such functionality would be missing from release builds where asserts
559 are disabled. If you want to assert return value of a critical function
560 call, make the call outside assert and place the return value to variable
561 and then assert value of that variable.
563 - For strings containing multiple sentences, use a single space after periods
564 (not two, not zero, just one).
566 - If you use a system specific feature, do not add #ifdef __CRAY__ or
567 something like that. Rather write a check for that feature for
568 configure.ac, and use a meaningful macro name in the source.
570 - Always prototype global functions in the appropriate header file. Local
571 functions should always be declared as static. To catch these and some
572 other problems please use the following warning options "-Wall
573 -Wpointer-arith -Wcast-align -Wmissing-prototypes -Wmissing-declarations
574 -Wstrict-prototypes -Wnested-externs -Wl,--no-add-needed" if you use gcc.
576 - Always check compilation with the configure option --enable-debug set.
578 - Header files should be compatible with C++ but code (.c) files need not
579 be. This means some C++ keywords (like "this" or "class") may not be used
580 in header files. It also means casts on void pointers (which should be
581 avoided in C files) must be used in headers.
583 - To assign null pointer, or to compare against one, use 'NULL' in C code,
584 and 'nullptr' in C++ code.
586 - If you send patches, use "diff -u" (or "diff -r -u"). "svn diff" works
587 correctly without extra parameters.
589 For further information, see:
590 <http://www.freeciv.org/wiki/How_to_Contribute>.
592 Also, name patch files descriptively (e.g. "fix-foo-bug-0.patch" is good,
593 but "freeciv.patch" is not).
595 - When doing a "diff" for a patch, be sure to exclude unnecessary files by
596 using the "-X" argument to "diff". E.g.:
598 % diff -ruN -Xdiff_ignore freeciv_svn freeciv >/tmp/fix-foo-bug-0.patch
600 A suggested "diff_ignore" file is included in the Freeciv distribution.
602 ============================================================================