<html>
<head>
    <base href="https://wiki.asterisk.org/wiki">
            <link rel="stylesheet" href="/wiki/s/en/2171/18/9/_/styles/combined.css?spaceKey=AST&amp;forWysiwyg=true" type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://wiki.asterisk.org/wiki/display/AST/Coding+Guidelines">Coding Guidelines</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://wiki.asterisk.org/wiki/display/~kmoore">Kinsey Moore</a>
    </h4>
        <div id="versionComment">
        <b>Comment:</b>
        add a comment about whitespace changes<br />
    </div>
        <br/>
                         <h4>Changes (2)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >* Don&#39;t annotate your changes with comments like &quot;/\* JMG 4/20/04 \*/&quot;;  Comments should explain what the code does, not when something was changed or who changed it. If you have done a larger contribution, make sure that you are added to the CREDITS file. <br> <br></td></tr>
            <tr><td class="diff-deleted-lines" style="color:#999;background-color:#fdd;text-decoration:line-through;">* Don&#39;t make unnecessary whitespace changes throughout the code.  If you make changes, submit them to the tracker as separate patches that only include whitespace and formatting changes. <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">* Don&#39;t make unnecessary whitespace changes throughout the code if that is not the goal of the task at hand. <br>** If you do want to make whitespace and formatting changes, submit them to the tracker as separate patches that only include whitespace and formatting changes.  Whitespace and formatting changes should only ever go into trunk. <br></td></tr>
            <tr><td class="diff-unchanged" > <br>* Don&#39;t use C+\+ type (//) comments. <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        
<div>
<ul>
    <li><a href='#CodingGuidelines-Introduction'>1. Introduction</a></li>
    <li><a href='#CodingGuidelines-Guidelines'>2. Guidelines</a></li>
<ul>
    <li><a href='#CodingGuidelines-GeneralRules'>2.1. General Rules</a></li>
    <li><a href='#CodingGuidelines-Filestructureandheaderinclusion'>2.2. File structure and header inclusion</a></li>
    <li><a href='#CodingGuidelines-Declarationoffunctionsandvariables'>2.3. Declaration of functions and variables</a></li>
    <li><a href='#CodingGuidelines-Structurealignmentandpadding'>2.4. Structure alignment and padding</a></li>
    <li><a href='#CodingGuidelines-UsetheinternalAPI'>2.5. Use the internal API</a></li>
    <li><a href='#CodingGuidelines-Codeformatting'>2.6. Code formatting</a></li>
<ul>
    <li><a href='#CodingGuidelines-Functions%3A'>2.6.1. Functions:</a></li>
    <li><a href='#CodingGuidelines-Ifstatements%3A'>2.6.2. If statements:</a></li>
    <li><a href='#CodingGuidelines-Casestatements%3A'>2.6.3. Case statements:</a></li>
    <li><a href='#CodingGuidelines-Nonestedstatementswithoutbraces'>2.6.4. No nested statements without braces</a></li>
</ul>
    <li><a href='#CodingGuidelines-Labels%2Fgotoareacceptable'>2.7. Labels/goto are acceptable</a></li>
    <li><a href='#CodingGuidelines-Donotcast%27void%5C%27'>2.8. Do not cast 'void *'</a></li>
    <li><a href='#CodingGuidelines-Functionnaming'>2.9. Function naming</a></li>
    <li><a href='#CodingGuidelines-Variablefunctionargumentparsing'>2.10. Variable function argument parsing</a></li>
    <li><a href='#CodingGuidelines-Variablenaming'>2.11. Variable naming</a></li>
<ul>
    <li><a href='#CodingGuidelines-Globalvariables'>2.11.1. Global variables</a></li>
</ul>
    <li><a href='#CodingGuidelines-Don%27tuseunnecessarytypedef%27s'>2.12. Don't use unnecessary typedef's</a></li>
    <li><a href='#CodingGuidelines-Useenumsinsteadof%23definewherepossible'>2.13. Use enums instead of #define where possible</a></li>
    <li><a href='#CodingGuidelines-Stringhandling'>2.14. String handling</a></li>
    <li><a href='#CodingGuidelines-Stringconversions'>2.15. String conversions</a></li>
    <li><a href='#CodingGuidelines-Useoffunctions'>2.16. Use of functions</a></li>
    <li><a href='#CodingGuidelines-Handlingofpointersandallocations'>2.17. Handling of pointers and allocations</a></li>
<ul>
    <li><a href='#CodingGuidelines-Useconstonpointerargumentsifpossible'>2.17.1. Use const on pointer arguments if possible</a></li>
    <li><a href='#CodingGuidelines-Donotcreateyourownlinkedlistcodereuse%5C%21'>2.17.2. Do not create your own linked list code - reuse!</a></li>
    <li><a href='#CodingGuidelines-Allocationsforstructures'>2.17.3. Allocations for structures</a></li>
    <li><a href='#CodingGuidelines-StringDuplications'>2.17.4. String Duplications</a></li>
</ul>
    <li><a href='#CodingGuidelines-CLICommands'>2.18. CLI Commands</a></li>
    <li><a href='#CodingGuidelines-Newdialplanapplications%2Ffunctions'>2.19. New dialplan applications/functions</a></li>
    <li><a href='#CodingGuidelines-DoxygenAPIDocumentationGuidelines'>2.20. Doxygen API Documentation Guidelines</a></li>
    <li><a href='#CodingGuidelines-Finishingupbeforeyousubmityourcode'>2.21. Finishing up before you submit your code</a></li>
    <li><a href='#CodingGuidelines-Creatingnewmanagerevents%3F'>2.22. Creating new manager events?</a></li>
</ul>
</ul></div>

<h1><a name="CodingGuidelines-Introduction"></a>1. Introduction</h1>

<p>This document gives some basic indication on how the asterisk code is structured.  Please read it to the end to understand in detail how the asterisk code is organized, and to know how to extend asterisk or contribute new code.</p>

<p>We are looking forward to your contributions to Asterisk - the Open Source PBX&#33; As Asterisk is a large and in some parts very time-sensitive application, the code base needs to conform to a common set of coding rules so that many developers can enhance and maintain the code. Code also needs to be reviewed and tested so that it works and follows the general architecture and guide-lines, and is well documented.</p>

<p>Asterisk is published under a dual-licensing scheme by Digium.  To be accepted into the codebase, all non-trivial changes must be licensed to Digium. For more information, see the electronic license agreement on <a href="https://issues.asterisk.org/" class="external-link" rel="nofollow">https://issues.asterisk.org/</a>.</p>

<p>Patches should be in the form of a unified (-u) diff, made from a checkout from subversion.</p>

<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>/usr/src/asterisk$ svn diff &gt; mypatch
</pre>
</div></div>

<p>If you would like to only include changes to certain files in the patch, you can list them in the "svn diff" command:</p>

<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>/usr/src/asterisk$ svn diff somefile.c someotherfile.c &gt; mypatch
</pre>
</div></div>

<h1><a name="CodingGuidelines-Guidelines"></a>2. Guidelines</h1>

<h2><a name="CodingGuidelines-GeneralRules"></a>2.1. General Rules</h2>

<ul>
        <li>Indent code using tabs, not spaces.</li>
</ul>


<ul>
        <li>All code, filenames, function names and comments must be in ENGLISH.</li>
</ul>


<ul>
        <li>Don't annotate your changes with comments like "/&#42; JMG 4/20/04 &#42;/";  Comments should explain what the code does, not when something was changed or who changed it. If you have done a larger contribution, make sure that you are added to the CREDITS file.</li>
</ul>


<ul>
        <li>Don't make unnecessary whitespace changes throughout the code if that is not the goal of the task at hand.
        <ul>
                <li>If you do want to make whitespace and formatting changes, submit them to the tracker as separate patches that only include whitespace and formatting changes.  Whitespace and formatting changes should only ever go into trunk.</li>
        </ul>
        </li>
</ul>


<ul>
        <li>Don't use C+&#43; type (//) comments.</li>
</ul>


<ul>
        <li>Try to match the existing formatting of the file you are working on.</li>
</ul>


<ul>
        <li>Use spaces instead of tabs when aligning in-line comments or #defines (this makes your comments aligned even if the code is viewed with another tabsize)</li>
</ul>



<h2><a name="CodingGuidelines-Filestructureandheaderinclusion"></a>2.2. File structure and header inclusion</h2>

<p>Every C source file should start with a proper copyright and a brief description of the content of the file.  Following that, you should immediately put the following lines:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision: 231369 $")</pre>
</div></div>

<p>"asterisk.h" resolves OS and compiler dependencies for the basic set of unix functions (data types, system calls, basic I/O libraries) and the basic Asterisk APIs.  ASTERISK_FILE_VERSION() stores in the executable information about the file.</p>

<p>Next, you should #include extra headers according to the functionality that your file uses or implements. For each group of functions that you use there is a common header, which covers OS header dependencies and defines the 'external' API of those functions (the equivalent of 'public' members of a class).  As an example:</p>

<ul>
        <li>asterisk/module.h<br/>
&#42;*if you are implementing a module, this should be included in one of the files that are linked with the module.</li>
</ul>


<ul>
        <li>asterisk/io.h
        <ul>
                <li>access to extra file I/O functions (stat, fstat, playing with directories etc)</li>
        </ul>
        </li>
</ul>


<ul>
        <li>asterisk/network.h
        <ul>
                <li>basic network I/O - all of the socket library, select/poll, and asterisk-specific (usually either thread-safe or reentrant or both) functions to play with socket addresses.</li>
        </ul>
        </li>
</ul>


<ul>
        <li>asterisk/app.h
        <ul>
                <li>parsing of application arguments</li>
        </ul>
        </li>
</ul>


<ul>
        <li>asterisk/channel.h
        <ul>
                <li>struct ast_channel and functions to manipulate it</li>
        </ul>
        </li>
</ul>


<p>For more information look at the headers in include/asterisk/.  These files are usually self-sufficient, i.e. they recursively #include all the extra headers they need.</p>

<p>The equivalent of 'private' members of a class are either directly in the C source file, or in files named asterisk/mod_*.h to make it clear that they are not for inclusion by generic code.</p>

<p>Keep the number of header files small by not including them unnecessarily.  Don't cut&amp;paste list of header files from other sources, but only include those you really need. Apart from obvious cases (e.g. module.h which is almost always necessary) write a short comment next to each #include to explain why you need it.</p>

<h2><a name="CodingGuidelines-Declarationoffunctionsandvariables"></a>2.3. Declaration of functions and variables</h2>

<ul>
        <li>Do not declare variables mid-block (e.g. like recent GNU compilers support) since it is harder to read and not portable to GCC 2.95 and others.</li>
</ul>


<ul>
        <li>Functions and variables that are not intended to be used outside the module must be declared static. If you are compiling on a Linux platform that has the 'dwarves' package available, you can use the 'pglobal' tool from that package to check for unintended global variables or functions being exposed in your object files. Usage is very simple:</li>
</ul>


<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>$ pglobal \-vf &lt;path to .o file&gt;
</pre>
</div></div>

<ul>
        <li>When reading integer numeric input with scanf (or variants), do <em>NOT</em> use '%i' unless you specifically want to allow non-base-10 input; '%d' is always a better choice, since it will not silently turn numbers with leading zeros into base-8.</li>
</ul>


<ul>
        <li>Strings that are coming from input should not be used as the format argument to any printf-style function.</li>
</ul>


<h2><a name="CodingGuidelines-Structurealignmentandpadding"></a>2.4. Structure alignment and padding</h2>

<p>On many platforms, structure fields (in structures that are not marked 'packed') will be laid out by the compiler with gaps (padding) between them, in order to satisfy alignment requirements. As a simple example:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">struct foo {
       int bar;
       void *xyz;
}</pre>
</div></div>

<p>On nearly every 64-bit platform, this will result in 4 bytes of dead space between 'bar' and 'xyz', because pointers on 64-bit platforms must be aligned on 8-byte boundaries. Once you have your code written and tested, it may be worthwhile to review your structure definitions to look for problems of this nature. If you are on a Linux platform with the 'dwarves' package available, the 'pahole' tool from that package can be used to both check for padding issues of this type and also propose reorganized structure definitions to eliminate it. Usage is quite simple; for a structure named 'foo', the command would look something like this:</p>

<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>$ pahole \--reorganize \--show_reorg_steps \-C foo &lt;path to module&gt;
</pre>
</div></div>

<p>The 'pahole' tool has many other modes available, including some that will list all the structures declared in the module and the amount of padding in each one that could possibly be recovered.</p>

<h2><a name="CodingGuidelines-UsetheinternalAPI"></a>2.5. Use the internal API</h2>

<p>Make sure you are aware of the string and data handling functions that exist within Asterisk to enhance portability and in some cases to produce more secure and thread-safe code. Check utils.c/utils.h for these.</p>

<p>If you need to create a detached thread, use the ast_pthread_create_detached() normally or ast_pthread_create_detached_background() for a thread with a smaller stack size.  This reduces the replication of the code to handle the pthread_attr_t structure.</p>

<h2><a name="CodingGuidelines-Codeformatting"></a>2.6. Code formatting</h2>

<p>Roughly, Asterisk code formatting guidelines are generally equivalent to the following:</p>

<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>\# indent \-i4 \-ts4 \-br \-brs \-cdw \-lp \-ce \-nbfda \-npcs \-nprs \-npsl \-nbbo \-saf \-sai \-saw \-cs \-l90 foo.c
</pre>
</div></div>

<p>this means in verbose:</p>
<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre> -i4:    indent level 4
 -ts4:   tab size 4
 -br:    braces on if line
 -brs:   braces on struct decl line
 -cdw:   cuddle do while
 -lp:    line up continuation below parenthesis
 -ce:    cuddle else
 -nbfda: dont break function decl args
 -npcs:  no space after function call names
 -nprs:  no space after parentheses
 -npsl:  dont break procedure type
 -saf:   space after for
 -sai:   space after if
 -saw:   space after while
 -cs:    space after cast
 -l90:  line length 90 columns
</pre>
</div></div>

<p>Function calls and arguments should be spaced in a consistent way across the codebase.</p>
<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>        GOOD: foo(arg1, arg2);
        BAD: foo(arg1,arg2);
        BAD: foo (arg1, arg2);
        BAD: foo( arg1, arg2 );
        BAD: foo(arg1, arg2,arg3);
</pre>
</div></div>

<p>Don't treat keywords (if, while, do, return) as if they were functions; leave space between the keyword and the expression used (if any). For 'return', don't even put parentheses around the expression, since they are not required.</p>

<p>There is no shortage of whitespace characters <img class="emoticon" src="/wiki/images/icons/emoticons/smile.gif" height="20" width="20" align="absmiddle" alt="" border="0"/> Use them when they make the code easier to read. For example:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">for (str=foo;str;str=str-&gt;next)</pre>
</div></div>
<p>is harder to read than</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">for (str = foo; str; str = str-&gt;next)</pre>
</div></div>
<p>Following are examples of how code should be formatted.</p>

<h3><a name="CodingGuidelines-Functions%3A"></a>2.6.1. Functions:</h3>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">int foo(int a, char *s)
{
        return 0;
}</pre>
</div></div>

<h3><a name="CodingGuidelines-Ifstatements%3A"></a>2.6.2. If statements:</h3>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">if (foo) {
        bar();
} else {
        blah();
}</pre>
</div></div>

<h3><a name="CodingGuidelines-Casestatements%3A"></a>2.6.3. Case statements:</h3>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">switch (foo) {
case BAR:
        blah();
        break;
case OTHER:
        other();
        break;
}</pre>
</div></div>

<h3><a name="CodingGuidelines-Nonestedstatementswithoutbraces"></a>2.6.4. No nested statements without braces</h3>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">for (x = 0; x &lt; 5; x++)
        if (foo)
                if (bar)
                        baz();</pre>
</div></div>

<p>Instead, do:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">for (x = 0; x &lt; 5; x++) {
        if (foo) {
                if (bar) {
                        baz();
                }
        }
}</pre>
</div></div>

<p>Always use braces around the statements following an if/for/while construct, even if not strictly necessary, as it reduces future possible problems.</p>

<p>Don't build code like this:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">if (foo) {
        /* .... 50 lines of code ... */
} else {
        result = 0;
        return;
}</pre>
</div></div>
<p>Instead, try to minimize the number of lines of code that need to be indented, by only indenting the shortest case of the 'if' statement, like so:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">if (!foo) {
        result = 0;
        return;
}

.... 50 lines of code ....</pre>
</div></div>

<p>When this technique is used properly, it makes functions much easier to read and follow, especially those with more than one or two 'setup' operations that must succeed for the rest of the function to be able to execute.</p>

<h2><a name="CodingGuidelines-Labels%2Fgotoareacceptable"></a>2.7. Labels/goto are acceptable</h2>

<p>Proper use of this technique may occasionally result in the need for a label/goto combination so that error/failure conditions can exit the<br/>
function while still performing proper cleanup. This is not a bad thing&#33;  Use of goto in this situation is encouraged, since it removes the need<br/>
for excess code indenting without requiring duplication of cleanup code.</p>

<h2><a name="CodingGuidelines-Donotcast%27void%5C%27"></a>2.8. Do not cast 'void &#42;'</h2>

<p>Do not explicitly cast 'void &#42;' into any other type, nor should you cast any other type into 'void &#42;'. Implicit casts to/from 'void &#42;' are explicitly allowed by the C specification. This means the results of malloc(), calloc(), alloca(), and similar functions do not <em>ever</em> need to be cast to a specific type, and when you are passing a pointer to (for example) a callback function that accepts a 'void &#42;' you do not need to cast into that type.</p>

<h2><a name="CodingGuidelines-Functionnaming"></a>2.9. Function naming</h2>

<p>All public functions (those not marked 'static'), must be named "ast_&lt;something&gt;" and have a descriptive name.</p>

<p>As an example, suppose you wanted to take a local function "find_feature", defined as static in a file, and used only in that file, and make it public, and use it in other files. You will have to remove the "static" declaration and define a prototype in an appropriate header file (usually in include/asterisk). A more specific name should be given, such as "ast_find_call_feature".</p>

<h2><a name="CodingGuidelines-Variablefunctionargumentparsing"></a>2.10. Variable function argument parsing</h2>

<p>Functions with a variable amount of arguments need a 'sentinel' when called. Newer GNU C compilers are fine if you use NULL for this. Older versions (pre 4) don't like this.  You should use the constant SENTINEL.  This one is defined in include/asterisk/compiler.h</p>

<h2><a name="CodingGuidelines-Variablenaming"></a>2.11. Variable naming</h2>

<h3><a name="CodingGuidelines-Globalvariables"></a>2.11.1. Global variables</h3>

<p>Name global variables (or local variables when you have a lot of them or are in a long function) something that will make sense to aliens who<br/>
find your code in 100 years.  All variable names should be in lower case, except when following external APIs or specifications that normally<br/>
use upper&#45; or mixed-case variable names; in that situation, it is preferable to follow the external API/specification for ease of understanding.</p>

<p>Make some indication in the name of global variables which represent options that they are in fact intended to be global.<br/>
e.g.: <tt>static char global_something</tt><tt>[80]</tt></p>

<h2><a name="CodingGuidelines-Don%27tuseunnecessarytypedef%27s"></a>2.12. Don't use unnecessary typedef's</h2>

<p>Don't use 'typedef' just to shorten the amount of typing; there is no substantial benefit in this:<br/>
<tt>struct foo { int bar; }; typedef struct foo foo_t;</tt></p>

<p>In fact, don't use 'variable type' suffixes at all; it's much preferable to just type 'struct foo' rather than 'foo_s'.</p>

<h2><a name="CodingGuidelines-Useenumsinsteadof%23definewherepossible"></a>2.13. Use enums instead of #define where possible</h2>

<p>Use enums rather than long lists of #define-d numeric constants when possible; this allows structure members, local variables and function arguments to be declared as using the enum's type. For example:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">enum option {
  OPT_FOO = 1,
  OPT_BAR = 2,
  OPT_BAZ = 4,
};

static enum option global_option;

static handle_option(const enum option opt)
{
  ...
}</pre>
</div></div>

<p>Note: The compiler will <em>not</em> force you to pass an entry from the enum as an argument to this function; this recommendation serves only to make<br/>
the code clearer and somewhat self-documenting. In addition, when using switch/case blocks that switch on enum values, the compiler will warn you if you forget to handle one or more of the enum values, which can be handy.</p>

<h2><a name="CodingGuidelines-Stringhandling"></a>2.14. String handling</h2>

<p>Don't use strncpy for copying whole strings; it does not guarantee that the output buffer will be null-terminated. Use ast_copy_string instead, which is also slightly more efficient (and allows passing the actual buffer size, which makes the code clearer).</p>

<p>Don't use ast_copy_string (or any length-limited copy function) for copying fixed (known at compile time) strings into buffers, if the buffer is something that has been allocated in the function doing the copying. In that case, you know at the time you are writing the code whether the buffer is large enough for the fixed string or not, and if it's not, your code won't work anyway&#33;  Use strcpy() for this operation, or directly set the first two characters of the buffer if you are just trying to store a one character string in the buffer. If you are trying to 'empty' the buffer, just store a single NULL character ('\0') in the first byte of the buffer; nothing else is needed, and any other method is wasteful.</p>

<p>In addition, if the previous operations in the function have already determined that the buffer in use is adequately sized to hold the string<br/>
you wish to put into it (even if you did not allocate the buffer yourself), use a direct strcpy(), as it can be inlined and optimized to simple<br/>
processor operations, unlike ast_copy_string().</p>

<h2><a name="CodingGuidelines-Stringconversions"></a>2.15. String conversions</h2>

<p>When converting from strings to integers or floats, use the sscanf function in preference to the atoi and atof family of functions, as sscanf detects errors.  Always check the return value of sscanf to verify that your numeric variables successfully scanned before using them.  Also, to avoid a potential libc bug, always specify a maximum width for each conversion specifier, including integers and floats.  A good length for both integers and floats is 30, as this is more than generous, even if you're using doubles or long integers.</p>

<h2><a name="CodingGuidelines-Useoffunctions"></a>2.16. Use of functions</h2>

<p>For the sake of uclibc, do not use index, bcopy or bzero; use strchr(), memset(), and memmove() instead. uclibc can be configured to supply these functions, but we can save these users time and consternation if we abstain from using these functions.</p>

<p>When making applications, always ast_strdupa(data) to a local pointer if you intend to parse the incoming data string.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">if (data) {
                mydata = ast_strdupa(data);
        }</pre>
</div></div>

<p>Use the argument parsing macros to declare arguments and parse them, i.e.:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">AST_DECLARE_APP_ARGS(args,
                AST_APP_ARG(arg1);
                AST_APP_ARG(arg2);
                AST_APP_ARG(arg3);
        );
        parse = ast_strdupa(data);
        AST_STANDARD_APP_ARGS(args, parse);</pre>
</div></div>

<p>Make sure you are not duplicating any functionality already found in an API call somewhere.  If you are duplicating functionality found in<br/>
another static function, consider the value of creating a new API call which can be shared.</p>

<h2><a name="CodingGuidelines-Handlingofpointersandallocations"></a>2.17. Handling of pointers and allocations</h2>

<h3><a name="CodingGuidelines-Useconstonpointerargumentsifpossible"></a>2.17.1. Use const on pointer arguments if possible</h3>

<p>Use const on pointer arguments which your function will not be modifying, as this allows the compiler to make certain optimizations. In general, use 'const' on any argument that you have no direct intention of modifying, as it can catch logic/typing errors in your code when you use the argument variable in a way that you did not intend.</p>

<h3><a name="CodingGuidelines-Donotcreateyourownlinkedlistcodereuse%5C%21"></a>2.17.2. Do not create your own linked list code - reuse&#33;</h3>

<p>As a common example of this point, make an effort to use the lockable linked-list macros found in include/asterisk/linkedlists.h. They are<br/>
efficient, easy to use and provide every operation that should be necessary for managing a singly-linked list (if something is missing,<br/>
let us know&#33;). Just because you see other open-coded list implementations in the source tree is no reason to continue making new copies of<br/>
that code... There are also a number of common string manipulation and timeval manipulation functions in asterisk/strings.h and asterisk/time.h;<br/>
use them when possible.</p>

<h3><a name="CodingGuidelines-Allocationsforstructures"></a>2.17.3. Allocations for structures</h3>

<p>When allocating/zeroing memory for a structure, use code like this:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">struct foo *tmp;

...

tmp = ast_calloc(1, sizeof(*tmp));</pre>
</div></div>

<p>Avoid the combination of ast_malloc() and memset().  Instead, always use ast_calloc(). This will allocate and zero the memory in a single operation.  In the case that uninitialized memory is acceptable, there should be a comment in the code that states why this is the case.</p>

<p>Using sizeof(*tmp) instead of sizeof(struct foo) eliminates duplication of the 'struct foo' identifier, which makes the code easier to read and also ensures that if it is copy-and-pasted it won't require as much editing.</p>

<p>The ast_&#42; family of functions for memory allocation are functionally the same.  They just add an Asterisk log error message in the case that the allocation fails for some reason. This eliminates the need to generate custom messages throughout the code to log that this has occurred.</p>

<h3><a name="CodingGuidelines-StringDuplications"></a>2.17.4. String Duplications</h3>

<p>The functions strdup and strndup can <b>not</b> accept a NULL argument. This results in having code like this:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">if (str) {
                newstr = strdup(str);
        } else {
                newstr = NULL;
        }</pre>
</div></div>
<p>However, the ast_strdup and ast_strdupa functions will happily accept a NULL<br/>
argument without generating an error.  The same code can be written as:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">newstr = ast_strdup(str);</pre>
</div></div>
<p>Furthermore, it is unnecessary to have code that malloc/calloc's for the length of a string (+1 for the terminating '\0') and then using strncpy to copy the copy the string into the resulting buffer.  This is the exact same thing as using ast_strdup.</p>

<h2><a name="CodingGuidelines-CLICommands"></a>2.18. CLI Commands</h2>

<p>New CLI commands should be named using the module's name, followed by a verb and then any parameters that the command needs. For example:</p>
<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>*CLI&gt; iax2 show peer &lt;peername&gt;
</pre>
</div></div>
<p>not</p>
<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>*CLI&gt; show iax2 peer &lt;peername&gt;
</pre>
</div></div>

<h2><a name="CodingGuidelines-Newdialplanapplications%2Ffunctions"></a>2.19. New dialplan applications/functions</h2>

<p>There are two methods of adding functionality to the Asterisk dialplan: applications and functions. Applications (found generally in<br/>
the apps/ directory) should be collections of code that interact with a channel and/or user in some significant way. Functions (which can be<br/>
provided by any type of module) are used when the provided functionality is simple... getting/retrieving a value, for example. Functions should also be used when the operation is in no way related to a channel (a computation or string operation, for example).</p>

<p>Applications are registered and invoked using the ast_register_application function; see the apps/app_skel.c file for an example.</p>

<p>Functions are registered using 'struct ast_custom_function' structures and the ast_custom_function_register function.</p>

<h2><a name="CodingGuidelines-DoxygenAPIDocumentationGuidelines"></a>2.20. Doxygen API Documentation Guidelines</h2>

<p>When writing Asterisk API documentation the following format should be followed. Do not use the javadoc style.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">/*!
 * \brief Do interesting stuff.
 *
 * \param thing1 interesting parameter 1.
 * \param thing2 interesting parameter 2.
 *
 * This function does some interesting stuff.
 *
 * \retval zero on success
 * \retval -1 on error.
 */
int ast_interesting_stuff(int thing1, int thing2)
{
        return 0;
}</pre>
</div></div>

<p>Notice the use of the \param, \brief, and \return constructs.  These should be used to describe the corresponding pieces of the function being documented.  Also notice the blank line after the last \param directive.  All doxygen comments must be in one /*&#33; &#42;/ block.  If the function or struct does not need an extended description it can be left out.</p>

<p>Please make sure to review the doxygen manual and make liberal use of the \a, \code, \c, \b, \note, \li and \e modifiers as appropriate.</p>

<p>When documenting a 'static' function or an internal structure in a module, use the \internal modifier to ensure that the resulting documentation explicitly says 'for internal use only'.</p>

<p>When adding new API you should also attach a \since note because this will indicate to developers that this API did not exist before this version. It also has the benefit of making the resulting HTML documentation to group the changes for a single version.</p>

<p>Structures should be documented as follows.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Confluence; brush: c; gutter: false">/*!
 * \brief A very interesting structure.
 */
struct interesting_struct
{
        /*! \brief A data member. */
        int member1;

        int member2; /*!&lt; \brief Another data member. */
}</pre>
</div></div>
<p>Note that /<b>&#33; &#42;/ blocks document the construct immediately following them unless they are written, /</b>&#33;&lt; &#42;/, in which case they document the construct preceding them.</p>

<p>It is very much preferred that documentation is not done inline, as done in the previous example for member2.  The first reason for this is that it tends to encourage extremely brief, and often pointless, documentation since people try to keep the comment from making the line extremely long.  However, if you insist on using inline comments, please indent the documentation with spaces&#33;  That way, all of the comments are properly aligned, regardless of what tab size is being used for viewing the code.</p>

<h2><a name="CodingGuidelines-Finishingupbeforeyousubmityourcode"></a>2.21. Finishing up before you submit your code</h2>

<p>Before submitting a patch, <b>read</b> the actual patch file to be sure that all the changes you expect to be there are, and that there are no<br/>
surprising changes you did not expect. During your development, that part of Asterisk may have changed, so make sure you compare with the latest SVN.</p>

<p>If you are asked to make changes to your patch, there is a good chance the changes will introduce bugs, check it even more at this stage.<br/>
Also remember that the bug marshal or co-developer that adds comments is only human, they may be in error <img class="emoticon" src="/wiki/images/icons/emoticons/smile.gif" height="20" width="20" align="absmiddle" alt="" border="0"/></p>

<h2><a name="CodingGuidelines-Creatingnewmanagerevents%3F"></a>2.22. Creating new manager events?</h2>

<p>If you create new AMI events, please read manager.txt. Do not re-use existing headers for new purposes, but please re-use existing headers<br/>
for the same type of data.</p>

<p>Manager events that signal a status are required to have one event name, with a status header that shows the status.  The old style, with one event named "ThisEventOn" and another named "ThisEventOff", is no longer approved.</p>

<p>Check manager.txt for more information on manager and existing headers. Please update this file if you add new headers.</p>

    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;" class="grey">
                        <a href="https://wiki.asterisk.org/wiki/users/removespacenotification.action?spaceKey=AST">Stop watching space</a>
            <span style="padding: 0px 5px;">|</span>
                <a href="https://wiki.asterisk.org/wiki/users/editmyemailsettings.action">Change email notification preferences</a>
</div>
        <a href="https://wiki.asterisk.org/wiki/display/AST/Coding+Guidelines">View Online</a>
        |
        <a href="https://wiki.asterisk.org/wiki/pages/diffpagesbyversion.action?pageId=3702830&revisedVersion=20&originalVersion=19">View Changes</a>
                |
        <a href="https://wiki.asterisk.org/wiki/display/AST/Coding+Guidelines?showComments=true&amp;showCommentArea=true#addcomment">Add Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>