27ea53c10d42bc0d5db81665069d62e3c5889074
[dpdk.git] / doc / guides / guidelines / coding_style.rst
1 Coding Style
2 =============
3
4 Description
5 -----------
6
7 This document specifies the preferred style for source files in the DPDK source tree.
8 It is based on the Linux Kernel coding guidelines and the FreeBSD 7.2 Kernel Developer's Manual (see man style(9)), but was heavily modified for the needs of the DPDK.
9
10 General Guidelines
11 ------------------
12
13 The rules and guidelines given in this document cannot cover every situation, so the following general guidelines should be used as a fallback:
14
15 * The code style should be consistent within each individual file.
16 * In the case of creating new files, the style should be consistent within each file in a given directory or module.
17 * The primary reason for coding standards is to increase code readability and comprehensibility, therefore always use whatever option will make the code easiest to read.
18
19 Line length is recommended to be not more than 80 characters, including comments.
20 [Tab stop size should be assumed to be 8-characters wide].
21
22 .. note::
23
24         The above is recommendation, and not a hard limit.
25         However, it is expected that the recommendations should be followed in all but the rarest situations.
26
27 C Comment Style
28 ---------------
29
30 Usual Comments
31 ~~~~~~~~~~~~~~
32
33 These comments should be used in normal cases.
34 To document a public API, a doxygen-like format must be used: refer to Doxygen Documentation.
35
36 .. code-block:: c
37
38  /*
39   * VERY important single-line comments look like this.
40   */
41
42  /* Most single-line comments look like this. */
43
44  /*
45   * Multi-line comments look like this.  Make them real sentences. Fill
46   * them so they look like real paragraphs.
47   */
48
49 License Header
50 ~~~~~~~~~~~~~~
51
52 Each file should begin with a special comment containing the appropriate copyright and license for the file.
53 Generally this is the BSD License, except for code for Linux Kernel modules.
54 After any copyright header, a blank line should be left before any other contents, e.g. include statements in a C file.
55
56 C Preprocessor Directives
57 -------------------------
58
59 Header Includes
60 ~~~~~~~~~~~~~~~
61
62 In DPDK sources, the include files should be ordered as following:
63
64 #. libc includes (system includes first)
65 #. DPDK EAL includes
66 #. DPDK misc libraries includes
67 #. application-specific includes
68
69 Include files from the local application directory are included using quotes, while includes from other paths are included using angle brackets: "<>".
70
71 Example:
72
73 .. code-block:: c
74
75  #include <stdio.h>
76  #include <stdlib.h>
77
78  #include <rte_eal.h>
79
80  #include <rte_ring.h>
81  #include <rte_mempool.h>
82
83  #include "application.h"
84
85 Header File Guards
86 ~~~~~~~~~~~~~~~~~~
87
88 Headers should be protected against multiple inclusion with the usual:
89
90 .. code-block:: c
91
92    #ifndef _FILE_H_
93    #define _FILE_H_
94
95    /* Code */
96
97    #endif /* _FILE_H_ */
98
99
100 Macros
101 ~~~~~~
102
103 Do not ``#define`` or declare names except with the standard DPDK prefix: ``RTE_``.
104 This is to ensure there are no collisions with definitions in the application itself.
105
106 The names of "unsafe" macros (ones that have side effects), and the names of macros for manifest constants, are all in uppercase.
107
108 The expansions of expression-like macros are either a single token or have outer parentheses.
109 If a macro is an inline expansion of a function, the function name is all in lowercase and the macro has the same name all in uppercase.
110 If the macro encapsulates a compound statement, enclose it in a do-while loop, so that it can be used safely in if statements.
111 Any final statement-terminating semicolon should be supplied by the macro invocation rather than the macro, to make parsing easier for pretty-printers and editors.
112
113 For example:
114
115 .. code-block:: c
116
117  #define MACRO(x, y) do {                                        \
118          variable = (x) + (y);                                   \
119          (y) += 2;                                               \
120  } while(0)
121
122 .. note::
123
124  Wherever possible, enums and inline functions should be preferred to macros, since they provide additional degrees of type-safety and can allow compilers to emit extra warnings about unsafe code.
125
126 Conditional Compilation
127 ~~~~~~~~~~~~~~~~~~~~~~~
128
129 * When code is conditionally compiled using ``#ifdef`` or ``#if``, a comment may be added following the matching
130   ``#endif`` or ``#else`` to permit the reader to easily discern where conditionally compiled code regions end.
131 * This comment should be used only for (subjectively) long regions, regions greater than 20 lines, or where a series of nested ``#ifdef``'s may be confusing to the reader.
132   Exceptions may be made for cases where code is conditionally not compiled for the purposes of lint(1), or other tools, even though the uncompiled region may be small.
133 * The comment should be separated from the ``#endif`` or ``#else`` by a single space.
134 * For short conditionally compiled regions, a closing comment should not be used.
135 * The comment for ``#endif`` should match the expression used in the corresponding ``#if`` or ``#ifdef``.
136 * The comment for ``#else`` and ``#elif`` should match the inverse of the expression(s) used in the preceding ``#if`` and/or ``#elif`` statements.
137 * In the comments, the subexpression ``defined(FOO)`` is abbreviated as "FOO".
138   For the purposes of comments, ``#ifndef FOO`` is treated as ``#if !defined(FOO)``.
139
140 .. code-block:: c
141
142  #ifdef KTRACE
143  #include <sys/ktrace.h>
144  #endif
145
146  #ifdef COMPAT_43
147  /* A large region here, or other conditional code. */
148  #else /* !COMPAT_43 */
149  /* Or here. */
150  #endif /* COMPAT_43 */
151
152  #ifndef COMPAT_43
153  /* Yet another large region here, or other conditional code. */
154  #else /* COMPAT_43 */
155  /* Or here. */
156  #endif /* !COMPAT_43 */
157
158 .. note::
159
160  Conditional compilation should be used only when absolutely necessary, as it increases the number of target binaries that need to be built and tested.
161
162 C Types
163 -------
164
165 Integers
166 ~~~~~~~~
167
168 For fixed/minimum-size integer values, the project uses the form uintXX_t (from stdint.h) instead of older BSD-style integer identifiers of the form u_intXX_t.
169
170 Enumerations
171 ~~~~~~~~~~~~
172
173 * Enumeration values are all uppercase.
174
175 .. code-block:: c
176
177  enum enumtype { ONE, TWO } et;
178
179 * Enum types should be used in preference to macros #defining a set of (sequential) values.
180 * Enum types should be prefixed with ``rte_`` and the elements by a suitable prefix [generally starting ``RTE_<enum>_`` - where <enum> is a shortname for the enum type] to avoid namespace collisions.
181
182 Bitfields
183 ~~~~~~~~~
184
185 The developer should group bitfields that are included in the same integer, as follows:
186
187 .. code-block:: c
188
189  struct grehdr {
190    uint16_t rec:3,
191        srr:1,
192        seq:1,
193        key:1,
194        routing:1,
195        csum:1,
196        version:3,
197        reserved:4,
198        ack:1;
199  /* ... */
200  }
201
202 Variable Declarations
203 ~~~~~~~~~~~~~~~~~~~~~
204
205 In declarations, do not put any whitespace between asterisks and adjacent tokens, except for tokens that are identifiers related to types.
206 (These identifiers are the names of basic types, type qualifiers, and typedef-names other than the one being declared.)
207 Separate these identifiers from asterisks using a single space.
208
209 For example:
210
211 .. code-block:: c
212
213    int *x;         /* no space after asterisk */
214    int * const x;  /* space after asterisk when using a type qualifier */
215
216 * All externally-visible variables should have an ``rte_`` prefix in the name to avoid namespace collisions.
217 * Do not use uppercase letters - either in the form of ALL_UPPERCASE, or CamelCase - in variable names.
218   Lower-case letters and underscores only.
219
220 Structure Declarations
221 ~~~~~~~~~~~~~~~~~~~~~~
222
223 * In general, when declaring variables in new structures, declare them sorted by use, then by size (largest to smallest), and then in alphabetical order.
224   Sorting by use means that commonly used variables are used together and that the structure layout makes logical sense.
225   Ordering by size then ensures that as little padding is added to the structure as possible.
226 * For existing structures, additions to structures should be added to the end so for backward compatibility reasons.
227 * Each structure element gets its own line.
228 * Try to make the structure readable by aligning the member names using spaces as shown below.
229 * Names following extremely long types, which therefore cannot be easily aligned with the rest, should be separated by a single space.
230
231 .. code-block:: c
232
233  struct foo {
234          struct foo      *next;          /* List of active foo. */
235          struct mumble   amumble;        /* Comment for mumble. */
236          int             bar;            /* Try to align the comments. */
237          struct verylongtypename *baz;   /* Won't fit with other members */
238  };
239
240
241 * Major structures should be declared at the top of the file in which they are used, or in separate header files if they are used in multiple source files.
242 * Use of the structures should be by separate variable declarations and those declarations must be extern if they are declared in a header file.
243 * Externally visible structure definitions should have the structure name prefixed by ``rte_`` to avoid namespace collisions.
244
245 Queues
246 ~~~~~~
247
248 Use queue(3) macros rather than rolling your own lists, whenever possible.
249 Thus, the previous example would be better written:
250
251 .. code-block:: c
252
253  #include <sys/queue.h>
254
255  struct foo {
256          LIST_ENTRY(foo) link;      /* Use queue macros for foo lists. */
257          struct mumble   amumble;   /* Comment for mumble. */
258          int             bar;       /* Try to align the comments. */
259          struct verylongtypename *baz;   /* Won't fit with other members */
260  };
261  LIST_HEAD(, foo) foohead;          /* Head of global foo list. */
262
263
264 DPDK also provides an optimized way to store elements in lockless rings.
265 This should be used in all data-path code, when there are several consumer and/or producers to avoid locking for concurrent access.
266
267 Typedefs
268 ~~~~~~~~
269
270 Avoid using typedefs for structure types.
271
272 For example, use:
273
274 .. code-block:: c
275
276  struct my_struct_type {
277  /* ... */
278  };
279
280  struct my_struct_type my_var;
281
282
283 rather than:
284
285 .. code-block:: c
286
287  typedef struct my_struct_type {
288  /* ... */
289  } my_struct_type;
290
291  my_struct_type my_var
292
293
294 Typedefs are problematic because they do not properly hide their underlying type;
295 for example, you need to know if the typedef is the structure itself, as shown above, or a pointer to the structure.
296 In addition, they must be declared exactly once, whereas an incomplete structure type can be mentioned as many times as necessary.
297 Typedefs are difficult to use in stand-alone header files.
298 The header that defines the typedef must be included before the header that uses it, or by the header that uses it (which causes namespace pollution),
299 or there must be a back-door mechanism for obtaining the typedef.
300
301 Note that #defines used instead of typedefs also are problematic (since they do not propagate the pointer type correctly due to direct text replacement).
302 For example, ``#define pint int *`` does not work as expected, while ``typedef int *pint`` does work.
303 As stated when discussing macros, typedefs should be preferred to macros in cases like this.
304
305 When convention requires a typedef; make its name match the struct tag.
306 Avoid typedefs ending in ``_t``, except as specified in Standard C or by POSIX.
307
308 .. note::
309
310         It is recommended to use typedefs to define function pointer types, for reasons of code readability.
311         This is especially true when the function type is used as a parameter to another function.
312
313 For example:
314
315 .. code-block:: c
316
317         /**
318          * Definition of a remote launch function.
319          */
320         typedef int (lcore_function_t)(void *);
321
322         /* launch a function of lcore_function_t type */
323         int rte_eal_remote_launch(lcore_function_t *f, void *arg, unsigned slave_id);
324
325
326 C Indentation
327 -------------
328
329 General
330 ~~~~~~~
331
332 * Indentation is a hard tab, that is, a tab character, not a sequence of spaces,
333
334 .. note::
335
336         Global whitespace rule in DPDK, use tabs for indentation, spaces for alignment.
337
338 * Do not put any spaces before a tab for indentation.
339 * If you have to wrap a long statement, put the operator at the end of the line, and indent again.
340 * For control statements (if, while, etc.), continuation it is recommended that the next line be indented by two tabs, rather than one,
341   to prevent confusion as to whether the second line of the control statement forms part of the statement body or not.
342   Alternatively, the line continuation may use additional spaces to line up to an appropriately point on the preceding line, for example, to align to an opening brace.
343
344 .. note::
345
346         As with all style guidelines, code should match style already in use in an existing file.
347
348 .. code-block:: c
349
350  while (really_long_variable_name_1 == really_long_variable_name_2 &&
351      var3 == var4){  /* confusing to read as */
352      x = y + z;      /* control stmt body lines up with second line of */
353      a = b + c;      /* control statement itself if single indent used */
354  }
355
356  if (really_long_variable_name_1 == really_long_variable_name_2 &&
357          var3 == var4){  /* two tabs used */
358      x = y + z;          /* statement body no longer lines up */
359      a = b + c;
360  }
361
362  z = a + really + long + statement + that + needs +
363          two + lines + gets + indented + on + the +
364          second + and + subsequent + lines;
365
366
367 * Do not add whitespace at the end of a line.
368
369 * Do not add whitespace or a blank line at the end of a file.
370
371
372 Control Statements and Loops
373 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
374
375 * Include a space after keywords (if, while, for, return, switch).
376 * Do not use braces (``{`` and ``}``) for control statements with zero or just a single statement, unless that statement is more than a single line in which case the braces are permitted.
377
378 .. code-block:: c
379
380  for (p = buf; *p != '\0'; ++p)
381          ;       /* nothing */
382  for (;;)
383          stmt;
384  for (;;) {
385          z = a + really + long + statement + that + needs +
386                  two + lines + gets + indented + on + the +
387                  second + and + subsequent + lines;
388  }
389  for (;;) {
390          if (cond)
391                  stmt;
392  }
393  if (val != NULL)
394          val = realloc(val, newsize);
395
396
397 * Parts of a for loop may be left empty.
398
399 .. code-block:: c
400
401  for (; cnt < 15; cnt++) {
402          stmt1;
403          stmt2;
404  }
405
406 * Closing and opening braces go on the same line as the else keyword.
407 * Braces that are not necessary should be left out.
408
409 .. code-block:: c
410
411  if (test)
412          stmt;
413  else if (bar) {
414          stmt;
415          stmt;
416  } else
417          stmt;
418
419
420 Function Calls
421 ~~~~~~~~~~~~~~
422
423 * Do not use spaces after function names.
424 * Commas should have a space after them.
425 * No spaces after ``(`` or ``[`` or preceding the ``]`` or ``)`` characters.
426
427 .. code-block:: c
428
429         error = function(a1, a2);
430         if (error != 0)
431                 exit(error);
432
433
434 Operators
435 ~~~~~~~~~
436
437 * Unary operators do not require spaces, binary operators do.
438 * Do not use parentheses unless they are required for precedence or unless the statement is confusing without them.
439   However, remember that other people may be more easily confused than you.
440
441 Exit
442 ~~~~
443
444 Exits should be 0 on success, or 1 on failure.
445
446 .. code-block:: c
447
448          exit(0);        /*
449                           * Avoid obvious comments such as
450                           * "Exit 0 on success."
451                           */
452  }
453
454 Local Variables
455 ~~~~~~~~~~~~~~~
456
457 * Variables should be declared at the start of a block of code rather than in the middle.
458   The exception to this is when the variable is ``const`` in which case the declaration must be at the point of first use/assignment.
459 * When declaring variables in functions, multiple variables per line are OK.
460   However, if multiple declarations would cause the line to exceed a reasonable line length, begin a new set of declarations on the next line rather than using a line continuation.
461 * Be careful to not obfuscate the code by initializing variables in the declarations, only the last variable on a line should be initialized.
462   If multiple variables are to be initialised when defined, put one per line.
463 * Do not use function calls in initializers, except for ``const`` variables.
464
465 .. code-block:: c
466
467  int i = 0, j = 0, k = 0;  /* bad, too many initializer */
468
469  char a = 0;        /* OK, one variable per line with initializer */
470  char b = 0;
471
472  float x, y = 0.0;  /* OK, only last variable has initializer */
473
474
475 Casts and sizeof
476 ~~~~~~~~~~~~~~~~
477
478 * Casts and sizeof statements are not followed by a space.
479 * Always write sizeof statements with parenthesis.
480   The redundant parenthesis rules do not apply to sizeof(var) instances.
481
482 C Function Definition, Declaration and Use
483 -------------------------------------------
484
485 Prototypes
486 ~~~~~~~~~~
487
488 * It is recommended (and generally required by the compiler) that all non-static functions are prototyped somewhere.
489 * Functions local to one source module should be declared static, and should not be prototyped unless absolutely necessary.
490 * Functions used from other parts of code (external API) must be prototyped in the relevant include file.
491 * Function prototypes should be listed in a logical order, preferably alphabetical unless there is a compelling reason to use a different ordering.
492 * Functions that are used locally in more than one module go into a separate header file, for example, "extern.h".
493 * Do not use the ``__P`` macro.
494 * Functions that are part of an external API should be documented using Doxygen-like comments above declarations. See the Doxgen documentation topic for details.
495 * Functions that are part of the external API must have an ``rte_`` prefix on the function name.
496 * Do not use uppercase letters - either in the form of ALL_UPPERCASE, or CamelCase - in function names. Lower-case letters and underscores only.
497 * When prototyping functions, associate names with parameter types, for example:
498
499 .. code-block:: c
500
501  void function1(int fd); /* good */
502  void function2(int);    /* bad */
503
504 * Short function prototypes should be contained on a single line.
505   Longer prototypes, e.g. those with many parameters, can be split across multiple lines.
506   The second and subsequent lines should be further indented as for line statement continuations as described in the previous section.
507
508 .. code-block:: c
509
510  static char *function1(int _arg, const char *_arg2,
511         struct foo *_arg3,
512         struct bar *_arg4,
513         struct baz *_arg5);
514  static void usage(void);
515
516 .. note::
517
518         Unlike function definitions, the function prototypes do not need to place the function return type on a separate line.
519
520 Definitions
521 ~~~~~~~~~~~
522
523 * The function type should be on a line by itself preceding the function.
524 * The opening brace of the function body should be on a line by itself.
525
526 .. code-block:: c
527
528  static char *
529  function(int a1, int a2, float fl, int a4)
530  {
531
532
533 * Do not declare functions inside other functions.
534   ANSI C states that such declarations have file scope regardless of the nesting of the declaration.
535   Hiding file declarations in what appears to be a local scope is undesirable and will elicit complaints from a good compiler.
536 * Old-style (K&R) function declaration should not be used, use ANSI function declarations instead as shown below.
537 * Long argument lists should be wrapped as described above in the function prototypes section.
538
539 .. code-block:: c
540
541  /*
542   * All major routines should have a comment briefly describing what
543   * they do. The comment before the "main" routine should describe
544   * what the program does.
545   */
546  int
547  main(int argc, char *argv[])
548  {
549          char *ep;
550          long num;
551          int ch;
552
553 C Statement Style and Conventions
554 ---------------------------------
555
556 NULL Pointers
557 ~~~~~~~~~~~~~
558
559 * NULL is the preferred null pointer constant.
560   Use NULL instead of ``(type *)0`` or ``(type *)NULL``, except where the compiler does not know the destination type e.g. for variadic args to a function.
561 * Test pointers against NULL, for example, use:
562
563 .. code-block:: c
564
565  if (p == NULL) /* Good, compare pointer to NULL */
566
567  if (!p) /* Bad, using ! on pointer */
568
569
570 * Do not use ! for tests unless it is a boolean, for example, use:
571
572 .. code-block:: c
573
574         if (*p == '\0') /* check character against (char)0 */
575
576 Return Value
577 ~~~~~~~~~~~~
578
579 * Functions which create objects, or allocate memory, should return pointer types, and NULL on error.
580   The error type should be indicated may setting the variable ``rte_errno`` appropriately.
581 * Functions which work on bursts of packets, such as RX-like or TX-like functions, should return the number of packets handled.
582 * Other functions returning int should generally behave like system calls:
583   returning 0 on success and -1 on error, setting ``rte_errno`` to indicate the specific type of error.
584 * Where already standard in a given library, the alternative error approach may be used where the negative value is not -1 but is instead ``-errno`` if relevant, for example, ``-EINVAL``.
585   Note, however, to allow consistency across functions returning integer or pointer types, the previous approach is preferred for any new libraries.
586 * For functions where no error is possible, the function type should be ``void`` not ``int``.
587 * Routines returning ``void *`` should not have their return values cast to any pointer type.
588   (Typecasting can prevent the compiler from warning about missing prototypes as any implicit definition of a function returns int,
589   which, unlike ``void *``, needs a typecast to assign to a pointer variable.)
590
591 .. note::
592
593         The above rule about not typecasting ``void *`` applies to malloc, as well as to DPDK functions.
594
595 * Values in return statements should not be enclosed in parentheses.
596
597 Logging and Errors
598 ~~~~~~~~~~~~~~~~~~
599
600 In the DPDK environment, use the logging interface provided:
601
602 .. code-block:: c
603
604  #define RTE_LOGTYPE_TESTAPP1 RTE_LOGTYPE_USER1
605  #define RTE_LOGTYPE_TESTAPP2 RTE_LOGTYPE_USER2
606
607  /* enable these logs type */
608  rte_set_log_type(RTE_LOGTYPE_TESTAPP1, 1);
609  rte_set_log_type(RTE_LOGTYPE_TESTAPP2, 1);
610
611  /* log in debug level */
612  rte_set_log_level(RTE_LOG_DEBUG);
613  RTE_LOG(DEBUG, TESTAPP1, "this is is a debug level message\n");
614  RTE_LOG(INFO, TESTAPP1, "this is is a info level message\n");
615  RTE_LOG(WARNING, TESTAPP1, "this is is a warning level message\n");
616
617  /* log in info level */
618  rte_set_log_level(RTE_LOG_INFO);
619  RTE_LOG(DEBUG, TESTAPP2, "debug level message (not displayed)\n");
620
621 Branch Prediction
622 ~~~~~~~~~~~~~~~~~
623
624 * When a test is done in a critical zone (called often or in a data path) the code can use the ``likely()`` and ``unlikely()`` macros to indicate the expected, or preferred fast path.
625   They are expanded as a compiler builtin and allow the developer to indicate if the branch is likely to be taken or not. Example:
626
627 .. code-block:: c
628
629  #include <rte_branch_prediction.h>
630  if (likely(x > 1))
631    do_stuff();
632
633 .. note::
634
635         The use of ``likely()`` and ``unlikely()`` should only be done in performance critical paths,
636         and only when there is a clearly preferred path, or a measured performance increase gained from doing so.
637         These macros should be avoided in non-performance-critical code.
638
639 Static Variables and Functions
640 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
641
642 * All functions and variables that are local to a file must be declared as ``static`` because it can often help the compiler to do some optimizations (such as, inlining the code).
643 * Functions that should be inlined should to be declared as ``static inline`` and can be defined in a .c or a .h file.
644
645 .. note::
646         Static functions defined in a header file must be declared as ``static inline`` in order to prevent compiler warnings about the function being unused.
647
648 Const Attribute
649 ~~~~~~~~~~~~~~~
650
651 The ``const`` attribute should be used as often as possible when a variable is read-only.
652
653 Inline ASM in C code
654 ~~~~~~~~~~~~~~~~~~~~
655
656 The ``asm`` and ``volatile`` keywords do not have underscores. The AT&T syntax should be used.
657 Input and output operands should be named to avoid confusion, as shown in the following example:
658
659 .. code-block:: c
660
661         asm volatile("outb %[val], %[port]"
662                 : :
663                 [port] "dN" (port),
664                 [val] "a" (val));
665
666 Control Statements
667 ~~~~~~~~~~~~~~~~~~
668
669 * Forever loops are done with for statements, not while statements.
670 * Elements in a switch statement that cascade should have a FALLTHROUGH comment. For example:
671
672 .. code-block:: c
673
674          switch (ch) {         /* Indent the switch. */
675          case 'a':             /* Don't indent the case. */
676                  aflag = 1;    /* Indent case body one tab. */
677                  /* FALLTHROUGH */
678          case 'b':
679                  bflag = 1;
680                  break;
681          case '?':
682          default:
683                  usage();
684                  /* NOTREACHED */
685          }
686
687 Environment or Architecture-specific Sources
688 --------------------------------------------
689
690 In DPDK and DPDK applications, some code is specific to an architecture (i686, x86_64) or to an executive environment (bsdapp or linuxapp) and so on.
691 As far as is possible, all such instances of architecture or env-specific code should be provided via standard APIs in the EAL.
692
693 By convention, a file is common if it is not located in a directory indicating that it is specific.
694 For instance, a file located in a subdir of "x86_64" directory is specific to this architecture.
695 A file located in a subdir of "linuxapp" is specific to this execution environment.
696
697 .. note::
698
699         Code in DPDK libraries and applications should be generic.
700         The correct location for architecture or executive environment specific code is in the EAL.
701
702 When absolutely necessary, there are several ways to handle specific code:
703
704 * Use a ``#ifdef`` with the CONFIG option in the C code.
705   This can be done when the differences are small and they can be embedded in the same C file:
706
707 .. code-block: console
708
709    #ifdef RTE_ARCH_I686
710    toto();
711    #else
712    titi();
713    #endif
714
715 * Use the CONFIG option in the Makefile. This is done when the differences are more significant.
716   In this case, the code is split into two separate files that are architecture or environment specific.  This should only apply inside the EAL library.
717
718 .. note:
719
720         As in the linux kernel, the "CONFIG_" prefix is not used in C code.
721         This is only needed in Makefiles or shell scripts.
722
723 Per Architecture Sources
724 ~~~~~~~~~~~~~~~~~~~~~~~~
725
726 The following config options can be used:
727
728 * CONFIG_RTE_ARCH is a string that contains the name of the architecture.
729 * CONFIG_RTE_ARCH_I686, CONFIG_RTE_ARCH_X86_64, CONFIG_RTE_ARCH_X86_64_32 or CONFIG_RTE_ARCH_PPC_64 are defined only if we are building for those architectures.
730
731 Per Execution Environment Sources
732 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
733
734 The following config options can be used:
735
736 * CONFIG_RTE_EXEC_ENV is a string that contains the name of the executive environment.
737 * CONFIG_RTE_EXEC_ENV_BSDAPP or CONFIG_RTE_EXEC_ENV_LINUXAPP are defined only if we are building for this execution environment.
738
739 Doxygen Documentation
740 ---------------------
741
742 The API documentation is automatically generated in the DPDK framework.
743 That is why all files that are part of the public API must be documented using Doxygen syntax.
744
745 The public API comprises functions of DPDK that can be used by an external application that will use the SDK.
746 Only the Doxygen syntax described in the coding rules (this document) should be used in the code.
747 All the Doxygen features are described in the Doxygen manual online.
748
749 Documenting a Function
750 ~~~~~~~~~~~~~~~~~~~~~~
751
752 All public functions must be documented. The documentation is placed in the header file, above the declaration of the function.
753 The definition of the function may be documented, but using standard comments (not in doxygen format).
754 The following is an example of function documentation:
755
756 .. code-block:: c
757
758  /**
759   * Summary here; one sentence on one line (should not exceed 80 chars).
760   *
761   * A more detailed description goes here.
762   *
763   * A blank line forms a paragraph. There should be no trailing white-space
764   * anywhere.
765   *
766   * @param first
767   *   "@param" is a Doxygen directive to describe a function parameter. Like
768   *   some other directives, it takes a term/summary on the same line and a
769   *   description (this text) indented by 2 spaces on the next line. All
770   *   descriptive text should wrap at 80 chars, without going over.
771   *   Newlines are NOT supported within directives; if a newline would be
772   *   before this text, it would be appended to the general description above.
773   * @param second
774   *   There should be no newline between multiple directives (of the same
775   *   type).
776   *
777   * @return
778   *   "@return" is a different Doxygen directive to describe the return value
779   *   of a function, if there is any.
780   */
781  int rte_foo(int first, int second)
782
783
784 Documenting Files
785 ~~~~~~~~~~~~~~~~~
786
787 Each public file may start with a comment describing what the file does. For example:
788
789 .. code-block:: c
790
791  /**
792   * @file
793   * This file describes the coding rules of RTE.
794   *
795   * It contains the coding rules of C code, ASM code, reStructured
796   * Text documentation, and of course how to use doxygen to document
797   * public API.
798   */
799
800
801 Documenting Constants and Variables
802 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
803
804 Examples:
805
806 .. code-block:: c
807
808  /**
809   * The definition of a funny TRUE.
810   */
811  #define TRUE 0
812
813  #define TRUE 1 /**< another way to document a macro */
814
815  /**
816   * Frequency of the HPET counter in Hz
817   *
818   * @see rte_eal_hpet_init()
819   */
820  extern uint64_t eal_hpet_resolution_hz;
821
822
823 Documenting Structures
824 ~~~~~~~~~~~~~~~~~~~~~~
825
826 Public structures should also be documented.
827 The ``/**<`` sequence can be used to documented the fields of the structure, as shown in the following example:
828
829 .. code-block:: c
830
831  /**
832   * Structure describing a memzone, which is a contiguous portions of
833   * physical memory identified by a name.
834   */
835  struct rte_memzone {
836
837  #define MEMZONE_NAMESIZE 32
838    char name[MEMZONE_NAMESIZE]; /**< name of the memory zone */
839
840    phys_addr_t phys_addr;       /**< start physical address */
841    void *addr;                  /**< start virtual address */
842    uint64_t len;                /**< len of the memzone */
843
844    int socket_id;               /**< NUMA socket id */
845  };
846
847
848 See Also Sections
849 ~~~~~~~~~~~~~~~~~
850
851 The @see keyword can be used to highlight a link to an existing function, file, or URL.
852 This directive should be placed on one line, without anything else, at the bottom of the documentation header.
853
854 .. code-block:: c
855
856  /**
857   * (documentation of function, file, ...)
858   *
859   * @see rte_foo()
860   * @see eal_memzone.c
861   */