Professional Documents
Culture Documents
Internal Document
C Coding Standard
Release <Software Release Number>
<DocNum> Rev. X0
Document Version <1.2>
15 October, 2008
KWC-SWAT Team
2 Kyocera Proprietary
3 Export of this technology or software is regulated by the U.S. Government.
4 Diversion contrary to U.S. law prohibited.
6Data and information contained in or disclosed by this document are proprietary information of Kyocera
7Wireless Corp., and all rights therein are expressly reserved. By accepting this material, the recipient agrees that this material and
8the information contained therein are held in confidence and in trust and will not be used, copied, or reproduced in whole or in
9part, nor its contents revealed in any manner to others without the express written permission of Kyocera Wireless Corp.
10
11
1 Contents
2 Table of Contents
3
41 Introduction................................................................................................................................1
52 Naming Standards.....................................................................................................................2
6 2.1 General Considerations in Naming........................................................................................2
7 2.2 File Names.............................................................................................................................2
8 2.3 Variable and Function Names................................................................................................3
9 2.3.1 Basics...............................................................................................................................3
10 2.3.2 Visibility (scope) of Names.............................................................................................4
11 2.3.3 #define..............................................................................................................................4
12 2.3.4 typedef..............................................................................................................................5
13 2.3.5 enum.................................................................................................................................5
14 2.3.6 struct.................................................................................................................................5
15 2.4 Pseudo-Hungarian Notation...................................................................................................6
3 File Organization.......................................................................................................................7
16
18 D.1 Description..........................................................................................................................35
19 D.1.1 Speed -> Robustness Tradeoff......................................................................................35
20 D.1.2 ‘Helper’ Function Exception.........................................................................................35
21 D.2 Function Format..................................................................................................................35
22 D.2.1 Before we Begin: Embrace Paste & Replace................................................................35
23 D.2.2 Function Comments......................................................................................................36
24 D.2.3 Function Declaration.....................................................................................................37
25 D.2.4 Function Body...............................................................................................................38
26 D.2.5 Functional Logic...........................................................................................................39
27 D.2.6 Error Handling..............................................................................................................40
28 D.2.7 Output Validation (Success Case).................................................................................40
29 D.2.8 Cleanup.........................................................................................................................41
30 D.3 ‘THE’ example...................................................................................................................41
Appendix E Generic Status Codes.............................................................................................43
31
1 1 Introduction
2Consistency is desirable in many undertakings and software production is one of them. While
3there exist good reasons that programmers each like what they like in terms of code aesthetics,
4productivity increases across a large team of programmers when they all know what to expect,
5and how to understand it, when they read one another’s work. The fact that any one of them
6won’t like some aspects of the code they see — and even, the code they write — is far less im-
7portant to a business than the time and effort wasted in supporting the “individuality” of varying
8coding styles.
9 So we present a single Coding Standard for you to follow in doing your work. As a part of the
10large group of skilled engineers doing their programming here, you leave some of your prefer-
11ences behind and tolerate a few mildly-distasteful things you’ll find mandated in this standard.
12At the same time, you gain far more from not having to tolerate everything that all those other
14And that’s focusing entirely on stylistic preferences, perhaps the least critical aspect of what is
15gained from applying a Coding Standard. Much of this standard is focused on conventions that
16provide semantic context for you when reading code. And as you’ll see, we mandate a few things
18And yet there may be situations in which the standards laid out in this document are inappropri-
19ate or painfully inconvenient — engineers should consult with their team leads about how best to
20proceed. Although making exceptions is possible, questions will likely arise at code reviews. In
21general, it is best to involve those responsible for maintaining this set of coding standards when
22an exception seems necessary; it may be that the standards themselves should be changed.
1 2 Naming Standards
2The purpose of naming standards is twofold: to increase source code consistency across multiple
3projects and to provide semantic information to readers of the source. Such information includes
4intended usage, location of declarations, special behaviors, and sometimes type indicators.
9 Names are to be as long as necessary in order to convey relevant meaning about their contents or
10function. That said, it’s important to take a moment when creating a new name and focus on how
11best to convey its meaning succinctly. Using commonly known abbreviations, omitting of extra
12(though not all) vowels, using digits in place of words, etc — these are all desirable tricks to re-
14In general, names of 8 to 18 characters in length (not counting required prefixes and suffixes)
15turn out to be sufficient, although there will be exceptions. There is no set minimum or maxim-
16um length.
Projects tend to use brief (three- or four-character) acronyms to identify themselves. This prac-
17
Filename length is a matter of surprising relevance, since portions of filenames are used within
20
22Having declared a strong preference for succinct (as compared to needlessly long) names, we
23note that there exists no reason to constrain filenames to eight characters. This is not 1983. There
24may be cases where compatibility with third-party products or processes does require use of
25DOS-style filenames. Only team leads may make this determination and they are to make it
26loudly and publicly so everyone can understand that their project has special needs and is not the
27desired rule. Even in such cases, it is worth the team lead’s time in checking to see if such a re-
Filenames follow the same character rules as C language identifiers, with two further qualifica-
29
tions:
30
1 The major application of single-character names is as loop control variables in small loops, which is quite reasonable. Beyond
40
41that usage, however, one must be prepared to pay for the privilege of less typing when one’s code is reviewed.
6tions about underscores and capitalization (those conventions are explained in section 2.3).
7Keeping filenames lower-case without underscores avoids conflicts across the set of conventions
9 Also, Windows does its own mangling of upper and lower case in filenames for the purpose of
10display. We require that filenames not be subject to cross-platform difficulties. When creating a
11new source file, ensure that its name is entirely lower-case, despite whatever mangling the OS
2.3.1 Basics
14
15All names begin with a letter, not an underscore. Names end with a letter or digit, not an under-
16score. We have two different naming conventions for separating words within a variable name:
17underscores or Pascal and Camel casing. Underscores can be used with code close to the qct lay-
19Pascal/Camel case can be used in new code to reflect the newer style of code at large in the com-
20puter community. Pascal case convention capitalizes the first letter of each word and is what is
21used for function names. Camel case is like Pascal case, except the first letter of the name is
24 name_with_four_parts
26 FunctionWithFourParts
28 nameWithFourParts
We also encourage you to use the VerbNoun naming convention for functions. I.e. describe what
29
35
5underscore:
6 extern word16 projid_GlobalVar; // line in header file
7 Project ID is whatever the relevant team lead decides it is. Usually, it’s an indication of both the
8 code’s purpose and the organizational responsibility for it. There is much to be said for using
9project ID as the filename, at least as the leading part of the filename. The declaration line above
10would appear within the header file projid.h and a matching definition line would appear in
11projid.c.
12That being said, we are moving away from the use of underscores (qct code should be the only
13exception). So, do not get carried away with the prefixing of function names with many
14prefix/underscore combinations:
18It can be daunting to apply the prefix-the-project-id convention where project id’s are long, but
19consistency along with reasonable brevity of project id’s provides more benefit than pain. Those
20of you with C++ experience may find it comforting to equate this convention with the use of
Variables and function names not externally visible outside a source file (declared within func-
22
tions or declared as static at file level) do not have to be prefixed with the file name.
23
31
32
33
2.3.3 #define
34
Any item declared in a #define (constant, macro, etc) is to be entirely capitalized and under-
35
Wrap each macro argument in an extra set of parenthesis to avoid any undesired side effects:
40
41 #define MACRO_WITH_ARGS( Arg1, Arg2 ) projid_SomeFunc( (Arg1) + (Arg2), TRUE )
7By wrapping the macro in a block it let’s you use that macro as a normal single statement, such
8as after an if statement, without having your second call not associated with the if. It also lets you
2.3.4 typedef
11
12The names of typedef items have a form similar to that of most identifiers; the rules for capit-
13alization and prefixing with filename (if externally visible) apply.
14 typedef short projid_Word; // externally visible
15
16 static typedef int BigWord; // file-local
17There do exist some exceptions to the typedef convention — a few system-wide cases which
18are so broadly applied that they’re considered “generic” and for which brevity is the main value.
19Examples are word16, word32, boolean, etc.
2
20
2.3.5 enum
21
A.1.1
28
2.3.6 struct
29
36
Fields within structs follow the same name rules as other variables, except that there is no project
37
2 Of course, these “generic” typedefs obviate the need for the very simple examples given here; generally, typedefs are applied
51
52for structs and enums.
2A.1
3
8pect comes from the fact that identifiers end up looking like words in a transliterated Hungarian
10In general, there is little need for pseudo-Hungarian notation any longer. Given context-sensitive
11editors, powerful source code browsers, compilers and code-checking tools capable of semantic
12analysis, there just isn’t much that Hungarizing of code adds to one’s day in programming. Other
However, for teams that want to use it anyway, there are a few conventions to follow:
14
15 • The pseudo-Hungarian prefix is always lower-case and appears right next to the name
16 it precedes (that is, no underscores separating it from the rest of the name).
17 • The prefix appears at the very beginning of names for file-local variables and func-
18 tions.
19 • The prefix appears immediately after the underscore that follows the project id por-
20 tion for externally-visible variables and functions.
For example:
21
22 static word16 * pw16FileScopeVar; // file-local
23
24 word16 * projid_pw16GlobalVar; // externally visible
25The pseudo-Hungarian prefixes themselves may be defined by the team(s) upon which they are
26inflicted. Such teams are responsible for adequately documenting the meanings of all such pre-
27fixes and making that documentation available to anyone who wanders into the code.
1 3 File Organization
2A module (paired source files: filename.h and filename.c) is composed of related func-
3tions. Many small modules are not a problem; be generous in creating new ones. As a general
4rule of thumb, modules over about 1000 lines become awkward to maintain — consider splitting
5them up.
26 1)
27 2) Source file comment with copyright, version, and documentation information.
28 3) System includes (<> syntax) for those system header files which are needed only for
29 the code inside this source file, not those needed for the declarations appearing in this
30 file’s matching header file.
1 4) Non-system includes (“” syntax) for those non-system header files which are needed
2 only for the code inside this source file, not those needed for the declarations appear-
3 ing in this file’s matching header file. Note that this section always includes at least
4 the header file associated with this source file.
5 5) #defines for those constant values and macros used only within this source file.
6 6) Type declarations (struct, enum, typedef, etc) for those types used only within
7 this source file.
8 7) Declarations of file-local (static) functions.
9 8) Definitions of externally visible constants (variables declared as const), declared
10 within the matching header file.
11 9) Definitions of externally visible variables, declared within the matching header file.
12 10) Definitions of file-local constants (variables declared as const and static) used
13 only within this source file.
14 11) Definitions of file-local (static) variables.
15 12) Definitions of externally visible functions, declared within the matching header file.
16 13) Definitions of file-local (static) functions, declared within this source file (at #3.
where FILENAME reflects the file’s name (in this example, it would be filename.h). Note
24
that every line in the file besides the directives themselves appears inside the ifndef-endif pair.
25
These directives serve to prevent multiple inclusion of the header file and provide a handy identi-
26
29Header files have a standard block-style comment immediately after the file identifier. This com-
30ment includes bookkeeping items such as copyright, version, etc. Documentation information
31about the file’s purpose and contents may also appear here. There is a template upon which all
32header files are based, and this provides examples of what belongs in here. (See 7)
5this issue. The header file identifier (discussed in section 3.1.1) is expressly intended to make
3
6using #includes easier by avoiding all possibility of multiple inclusion and completely elimin-
8 The only #includes which should appear within a header file are those which resolve refer-
9ences that appear inside this header file — not in the matching source file. Any references which
10need resolving in the code there will be dealt with by #includes there.
12Variables are declared as extern in a header file when they physically reside in the matching
13source file, but are referenced by other header or source files. At no time is a variable defined in
16Functions are declared as extern in a header file when their code is located in the matching
17source file, and they are called from within other source files. At no time is a function defined in
18a header file.
If a function is not called from within other source files, its declaration does not use the extern
19
keyword and is not to appear in a header file, but rather within the matching source file.
20
22
23
25Like header files, source files have a standard block-style comment immediately after the file
26identifier. This comment includes bookkeeping items such as copyright, version, etc. Document-
27ation information about the file’s purpose and contents may also appear here. There is a template
28upon which all source files are based, and this provides examples of what belongs in here. (See
297)
3 We would encourage use of nested header files, to avoid placing upon people the burden of detecting all needed #includes,
65
66as well as dealing with ordering issues. We’ve considered the awful burden inflicted on the compiler during builds… but that’s
67what machines are for. Yet team leads are the ultimate decision-makers.
8plate header.
9 It is essential that you give a good description of what the function does before each function.
10You will not be the only one working on this function, so make the description clear enough for
11someone else to get a good idea of what the function should be doing before they have to start
12figuring out the code. And, no, the source code is not the description.
13Please keep this header information up to date as the function changes. Nothing is more annoy-
14ing than reading some function description about how the code below simply matches the incom-
15ing caller ID with a name from the Contacts listing, than to find out that now it looks it up, up-
18Within a function, if you are doing anything that requires you to pause for a moment and think,
19put a descriptive comment about the code logic you are using. It is far quicker to read a couple
20sentences about what the code should be doing than it is to figure out the code from scratch.
21Having a general idea in mind, then looking at the code will help the next person see what’s go-
22ing on much better than having to draw out the code flow on scratch paper. And be sure to update
24
3.3 Templates
25
26Attached in the appendixes are template header and source files with bare bone skeletons of the
27file header comments and function header comments. Cut and paste from these when creating a
28new file or a new function.
3.4 Copyright
29
30This is the one portion of the Coding Standard that we have to bring in the sharks… err, Law-
31yers, I mean. We have code that we get from Qualcomm on a regular basis with their chips; this
32is the dmss stuff. We have code that we got from Qualcomm when Kyocera Wireless Corp. was
33formed. And, we have source code that, believe it or not, we wrote all by ourselves.
1Fortunately, what we have to do is pretty simple. Any code that we modify, add a copyright date
2for Kyocera to it. Be sure not to remove any copyright info already in the file. You can move the
3line around to fit into our template place for copyright info, just don’t get rid of any.
4List out each year, separated by a comma. When that line gets too long (>80 columns), add an-
5other line below it.
6 Copyright (c) 2002, 2003 by Kyocera Wireless Corp. All Rights Reserved.
7Any source file that you find without any copyright info, just add our standard header and, if you
8know, the years that that file existed. So, if it was written in 2001 add:
9 Copyright (c) 2001, 2002, 2003 by Kyocera Wireless Corp. All Rights Reserved.
1 4 Code Formatting
74.2 Whitespace
8Use it. A lot.
9For details on whitespace required by this coding standard, we provide the following examples,
as well as any other examples throughout this document:
10
4
15 • Put a space after an open parenthesis, after a closing parenthesis, and after commas.
16 Put a space after a keyword (if, do, for, etc…) and before it’s parenthesis. Do not put
17 a space after a function name and its opening parenthesis:
18 until ( (a == b) && (c <= d) );
19 FunctionCall( FirstArg, SecondArg, ThirdArg );
20 • Do not put a space between the * pointer-dereference operator and the name to which
21 it applies:
22 a = *b;
27 •
28 • Put at least one blank line between variable and function declarations in header files:
29 extern word32 projid_Fargle;
4 No, we don’t show function-header or other types of comments in these examples. The point here is whitespace, not comment-
77
78ing. We hit you with that elsewhere.
1
2 extern boolean projid_Fargled;
3
4 extern void projid_FargleIt();
5 • Put at least one blank line between segments within a switch statement, except
6 where the segments are so short (one or two lines) that the entire switch fits cleanly
7 into a small area:
8 switch ( BigSwitchController )
9 {
10 case First:
11 DoSomething( Complex );
12 . . . // <--- several lines not shown
13 break;
14
15 case That:
16 DoSomething( EvenComplexer );
17 . . . // <--- again, lines not shown
18 break;
19
20 default:
21 DoNothing();
22 }
23 • Put at least three blank lines between function definitions in source files:
24 void
25 projid_SomeFunc() // in source file
26 {
27 } // projid_SomeFunc
28
29
30
31 void
32 projid_SomeOtherFunc()
33 {
34 } // projid_SomeOtherFunc
35Please contact those responsible for the standard in any case where a question about use of
36whitespace remains (so that the question may be answered with your input, and the standard up-
37dated).
39Lines are to be broken at length 80. While this may seem short, given today’s large monitors, it’s
40a sad truth that someone will print the code — and they’ll add line numbers — through a printing
41program that doesn’t wrap lines, onto a page that’s 80 characters wide. Even when you’re sure
42that something, an editor or a print filter or whatever, will always wrap lines… do you want it de-
43ciding where to break the line, or you? Put aside laziness, go with the inner artist, and make
Is evil. Don’t trust it. Don’t assume anyone else has learned it or really understood it.
46
47Logical conditions and mathematical calculations are to be fully parenthesized. Fully. Yes, even
48where it’s “obvious” what the intent of the expression is and the precedence rules “clearly” ap-
49ply. Such situations fall victim to typographical (&&, & ||, |, +, ++, etc) and pointer-dereferen-
Similar to complex conditions and mathematical operators, long loop control expressions are to
17
The indentation of the extra lines should match the starting point of the previous line’s condition.
25
26Although this isn’t the section on naming, it is worth noting that loop control variables are one of
27the very few items for which single-character names may be appropriate. If nothing else, this can
28shorten a loop control expression to where it fits cleanly onto an 80-character line.
30
31Two (2) spaces per level of indentation is used for new code. Always use spaces for indentation,
5
Indentation is always increased within braces (except as noted below for switch statements).
33
5 While not as close to the nerve as placement of braces, indentation style can seem pretty personal to programmers, too. Refer to
85
86the footnote on braces.
6 There are editor settings you should make to fit this convention. Note that some editors support the concept of indentation as
87
88distinct from tabs (for example, vi does it with the shiftwidth setting), and that capability is worth learning about and using. At
89the very least, you must configure your editor to replace tabs with spaces, if tabs are what you use to perform indenting.
1If-then-elses always have braces, as do all forms of loop. This consistency is more valuable than
2the rare savings of a few lines for skipping the braces around single-statement blocks.
9 • Braces for type declarations with subparts (structs, unions, enums) appear in column
10 0:
11 typedef enum // externally visible
12 {
13 ENUM_VAL_E = 42,
14 OTHER_VAL_E = 69
15 } projid_Blargle;
16 • Braces for nested code blocks (if-then-else bodies, loop bodies) appear on their own
17 lines at the indentation level of code where the block appears:
18 if ( FumingOverBracePlacement )
19 {
20 while ( Fuming )
21 {
22 CountToTen();
23 }
24 GetALife( AsSoonAsPossible );
25 }
26 else
27 {
28 HaveANiceDay( Today );
29 }
30 • The braces required for a switch statement appear on their own lines at the indenta-
31 tion level of the switch statement itself (similar to if-then-else braces). Braces are not
32 used for the segments within a switch statement:
33 switch ( ManyOptions )
34 {
35 case This:
36 DoSomething( Now );
37 break;
38 case That:
39 DoSomethingElse( Later );
40 break;
41 default:
42 DoNothing( Forever );
43 }
44 Note that the case values also appear at the indentation level of the braces. This is un-
45 usual, in that most code within braces is shifted at least one level to the right. This
46 convention keeps the actual code to be executed at its correct indentation level, while
47 visually separating out the values used in choosing which code to execute.
7 Placement of braces is a religious issue among programmers. We don’t intend to convert you. Prefer whatever you wish to
93
94prefer.
But we do require that you do it this way, preferences aside. The product of your efforts is not a demonstration of your
95preferences — it’s code that exists alongside that produced by lots of other people. Someone in that picture will not like
96something. Yet one thing must be done. Sorry, but cope with it.
184.10#ifdefs
19We encourage the indentation of #ifdefs on the same level as the surrounding code. Obviously,
20for any #ifdefs that are outside of a function (like most at the begginning of the source file), this
21will mean to just stick them in column one. But even within an #ifdef block, indent subsequent
22#ifdefs appropriately. Note, that the #ifdefs are indent separately from the actual code.
23
24 //===================================================================
25 void build_ch_menu( uigm_page_field_type* pf )
26 {
27 …
28 /* Now create the scroll bar */
29 bbox = pf->rect;
30 #ifdef UIMM_SCROLLBAR_ON_LEFT
31 bbox.x = 0;
32 bbox.dx = 3;
33 #else
34 bbox.x = bbox.x + bbox.dx - 3;
35 bbox.dx = 3;
36 #endif
37 …
38 }
39
40 //===================================================================
41 #ifdef TMC_1X
42 #include "srch.h" // Srch header file
43 #include "rxtx.h" // RXTX header file
44 #if ( TG != T_PC ) // Define for all targets except Unit Test
45 #include "therm.h" // Thermister header file
46 #define TMC_HAS_HW_CONFIG
47 #endif // TG!=T_PC
48 #endif // TMC_1X
49
50 //===================================================================
51 LOCAL void tmc_libraries_init_before_tasks_start( void )
52 {
1 …
2 #ifdef TMC_1X
3 db_init(); // Database services
4 enc_init();
5 #ifdef T_MSM5000 /* Decoder driver */
6 deint_init();
7 #else
8 #error code not present
9 #endif
10 #ifdef T_MSM5000
11 #ifdef T_MSM4500
12 #error code not present
13 #else // T_MSM4500
14 #ifndef FEATURE_DMOD_IMAGE_IN_ROM
15 #ifdef T_MSM6050
16 // For T_MSM6300 target, demod... is done by rf_init_delayed()
17 #ifndef FEATURE_MDSP_TASK
18 demod_download_image( TRUE );
19 #endif
20 #else
21 #error code not present
22 #endif // T_MSM6050
23 #endif // FEATURE_DMOD_IMAGE)_IN_ROM
24 #endif // T_MSM4500
25 #endif // T_MSM5000
26 …
27 }
28
29
30
31
32
33
34
1 5 Comments
2Comments can use either the C (/* … */) or C++ (// … ) style of comments. The C++ style are
3appropriately used for single line comments, or trailing comments. Any comment beyond a few
4lines should use the C style for the comment block.
9Every function definition is to be preceded by a block comment describing the purpose of the
10function, the arguments, the return value, and any side effects or dependencies.
All externally visible variables are to have a comment explaining the variable’s meaning and in-
11
12tended usage. Such a comment appears twice: at the declaration in the header file and also at the
13definition in the source file.
14Every #endif more than a few (on the order of 4) lines below its matching #if or #ifdef is
15to have a comment that shows the #if condition. Such comments are encouraged even when
16there are just a few lines, and they are required whenever nesting of #if/#ifdef directives ob-
18Comment lines within code are to be indented at the same level as surrounding code.
1 6 Miscellaneous
2Use include path directives rather than path information in #include statements.
3Switch statements are always to include a default case. Any fall-through (segment not ending
4in a break statement) must be explicitly commented as having been intended.
5All “magic numbers” should be avoided — define a constant.
6Explicitly initialize all variables before use, except where the nature of the platform’s memory
7management makes it unnecessary (and explicitly comment the absence of initialization in such
8cases).
10 Always declare the return type of functions – if the function returns nothing, use void rather
11than allowing the compiler to default to int.
12Always use the types provided by globally available typedefs (such as word8, word16,
13word32, int8, int16, int32, and boolean) rather than built-in types.
14All functions that can return an error status should be checked for an error return or explicitly ig-
15nored (i.e., casting the return value to (void)).
16Use NULL or ‘\0’ rather than 0 where appropriate.
17Avoid implicitly comparing against NULL or 0 in conditional tests:
18 if ( x != 0 )
19is preferable to
20 if ( x )
21but note that boolean values are testable in and of themselves. For instance:
22 boolean is_okay = TRUE;
23 . . .
24 if ( is_okay )
25 {
26 . . .
27is acceptable because it mirrors the use of boolean terms in natural language. There is little need
28for redundancy such as if ( is_okay == TRUE ). It is, however, important to limit such
29forms to actual boolean values and not make implicit use of the C language’s evaluation of math-
30ematical zero or end-of-string null character as being false (as noted above).
31Any local variable definition should appear within the smallest scope that includes all its uses.
32Try to (re)initialize variables near code that depends on an initialization value.
33Where practical, return from a function at the end of the code only. An exception should be made
34for argument validation – please return immediately.
1Explicit type casts should be viewed with some skepticism; a more appropriate type is often
2available and provides greater consistency throughout a variable’s scope. The same concern ap-
1 7 Revision History
1 /*===========================================================================
2
3 EXTERNAL FUNCTION DECLARATIONS
4
5 Declare any functions that this module (and it's source file) conceptually
6 owns, that are used in any other module.
7
8 ===========================================================================*/
9
10
11
12 /*===========================================================================
13 Basically, copy this description from the source file. You may need to
14 expand this a bit more, since they won't see the code and other source
15 file functions here in the header file.
16
17 FUNCTION TEMPLATE_FUNCTION_NAME
18
19 DESCRIPTION
20 Obviously, a description of the function goes here. Please,
21 pretty please with a cherry on top, I'm begging you, make this a good
22 description. Don't assume you'll be the only one working on it. Most likely
23 it will be some new person who's never even talked to you, who's trying to
24 fix it for an urgent CR that has to get done by noon, who'll have to figure
25 out what this function is supposed to do. Write the description for them.
26
27 DEPENDENCIES
28 List any dependcies here or "None".
29
30 RETURN VALUE
31 What does this return? If it returns just a few values, list them and when
32 it would return them.
33
34 e.g.
35 TRUE - If nv item #3 has a value.
36 TRUE - If the phone is in idle state
37 FALSE - We are roaming
38
39 The next state to be processed.
40
41 SIDE EFFECTS
42 List the other random variables your code affects, or the other functions
43 you call to secretly change things.
44
45 ===========================================================================*/
46 extern ReturnType template_FunctionName // this function name must begin with the name
47 // of this file if it is to be externalized
48 (
49 ParmType1 ParmName1, // description of Parm1
50 ParmType2 ParmName2 // description of Parm2
51 );
52
53 #endif // TEMPLATE_H
1 template_Close
2 Cleans up all variables used in these functions. Must call last.
3
4 INITIALIZATION AND SEQUENCING REQUIREMENTS
5 Any requirements, list here.
6 Must call template_Init() before any other function in this module.
7 Must call template_Close() after you're all done w/ this stuff.
8
9 Copyright (c) 2003 by Kyocera Wireless Corp. All Rights Reserved.
10 *====*====*====*====*====*====*====*====*====*====*====*====*====*====*====*/
11 // Note: 3 blank lines between sections here
12
13
14
15 /*===========================================================================
16
17 INCLUDE FILES FOR MODULE
18
19 List all necessary header files here. System header files use <>, our
20 header files, use "".
21
22 ===========================================================================*/
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include "target.h"
26 #include "task.h"
27 // Note: 3 blank lines between sections here
28
29
30
31 /*===========================================================================
32
33 LOCAL DEFINITIONS AND DECLARATIONS FOR MODULE
34
35 This section contains local definitions for constants, macros, types,
36 variables and other items needed by this module.
37
38 Place a comment for a description of the variable immediate after it, if
39 enough room on line, or on the following line.
40
41 ===========================================================================*/
42 /* Maximum search rates - This is the old 1X throttle
43 before the 8X mode testing was done. Note that during
44 8X mode testing these were lowered by 30 Hz. */
45
46 static int2 srch_rate_upper_limit = 130; // Hz
47 static int2 srch_rate_lower_limit = 120; // Hz
48
49 /*---------------------------------------------------------------------------
50 Separate areas of declarations using this type of comment.
51 ---------------------------------------------------------------------------*/
52 // Defines to support the proper dynamic throttle action
53 #define SRCH_RATE_UPPER_LIMIT ( srch_rate_upper_limit - srch_limit_rate_backoff \
54 - srch_limit_chip_backoff )
55 #define SRCH_RATE_LOWER_LIMIT ( srch_rate_lower_limit - srch_limit_rate_backoff \
56 - srch_limit_chip_backoff )
57
58 /*---------------------------------------------------------------------------
59 Separate areas of declarations using this type of comment.
60 ---------------------------------------------------------------------------*/
61 // Keeps track of the current state of the Searcher Task state machine.
62 srch_state_enum_type srch_state = SRCH_START_STATE;
63
64 // Parameters that control the behavior of the searcher task.
65 // These are settable by the base station via MCC
66 srch_parm_struct_type srch_parms;
67 // Note: 3 blank lines between sections here
68
69
70
71 /*===========================================================================
1
2 FUNCTION TEMPLATE_FUNCTION_NAME
3
4 DESCRIPTION
5 Obviously, a description of the function goes here. Please,
6 pretty please with a cherry on top, I'm begging you, make this a good
7 description. Don't assume you'll be the only one working on it. Most likely
8 it will be some new person who's never even talked to you, who's trying to
9 fix it for an urgent CR that has to get done by noon, who'll have to figure
10 out what this function is supposed to do. Write the description for them.
11
12 DEPENDENCIES
13 List any dependcies here or "None".
14
15 RETURN VALUE
16 What does this return? If it returns just a few values, list them and when
17 it would return them.
18
19 e.g.
20 TRUE - If nv item #3 has a value.
21 TRUE - If the phone is in idle state
22 FALSE - We are roaming
23
24 The next state to be processed.
25
26 SIDE EFFECTS
27 List the other random variables your code affects, or the other functions
28 you call to secretly change things.
29
30 ===========================================================================*/
31 ReturnType template_FunctionName // this function name must begin with the name
32 // of this file if it is to be externalized
33 (
34 ParmType1 ParmName1, // description of Parm1
35 ParmType2 ParmName2 // description of Parm2
36 )
37 {
38 /* work your magic in here, make the world a better place, save the day
39 or at least, make my phone do neat things */
40
41 /* LOGIC: For anything more complex than trivial addition give a few sentences
42 describing what you're doing, the logic you're using, and, most importantly,
43 why you're doing this. This way when someone is trying to figure out what the
44 heck is going on in your function they, at least, start with an idea of how
45 you're going about it. */
46
47 /*-------------------------------------------------------------------------
48 Sample statement layouts
49 -------------------------------------------------------------------------*/
50 // If statement. Even one line expressions must have braces around it
51 if ( Variable == Value )
52 {
53 i++;
54 }
55 else if ( ( Variable == Value ) &&
56 ( Test == Condition ) || MyStruct.Field > OtherStruct.Setting ) )
57 {
58 // ...
59 }
60 else
61 {
62 // ...
63 }
64
65 // Switch statement example
66 switch ( Choice )
67 {
68 case Choice = 1:
69 i++;
70 break;
71
1 case Choice = 2:
2 j++;
3 // fall through <-- explicitly state this
4
5 case Choice = 3:
6 k++;
7 DoSomething( ParmName1, ParmName2 );
8 break;
9
10 default:
11 ErrorMessage( MyMessage );
12 }
13
14 // for loop example
15 for ( int iIndexIntoNameList = 0; iIndexIntoNameList <= NameList.Length;
16 iIndexIntoNameList++ )
17 {
18 // ...
19 }
20
21 }
22
23
24
25 /*
26 Remember, no <TAB> characters. Use spaces. Set up your editor to use <space>.
27 Violators will be taken into the back room with a wet noodle and beatings
28 will ensue.
29
30 We are using an indent level of 2 spaces. I know, I know, you like 3 spaces,
31 and you there, in the back, you like 4, you Microsoft junkie you. And you over there
32 in the blue shirt you like using 8, 'cause that's what a real man/<TAB> would
33 use. Well, we're using 2 here in this shop, just set it up in your editor
34 settings and forget about it. And if you really don't like it ....
35 'indent -i2 myfile.c -o newfile.c'
36
37 Stick 3 blank lines between coding sections, this just helps to set them off.
38 */
2Ah, the subject of many conversations. Usually, with the end result of people storming out of the
3room with murderous looks upon their faces as they race off to their colleagues desk chairs to
4plant thumbtacks upon them.
5There is a lucid article about this subject on Jamie Zawinski’s site (he of the first version of Nets-
6cape fame) http://www.jwz.org/doc/tabs-vs-spaces.html. Go on read it, it only takes three
7minutes to read and I’ve got time before my next meeting. I’ll wait.
8Ok, I bet none of you actually read that. Oh well, his main point is that we use the word “tab” to
9mean different things: 1) how the code is indented; 2) how your editor reacts to an actual TAB
10character (0x09) in a file; 3) how your editor reacts to you pressing the <TAB> key on your key-
11board.
12Point 1, how the code is indented. This, is how many columns your code is indented. Two, three
13and four are all very common numbers for this. Some people use a more complicated method de-
15Point 2, how your editor reacts to reading a TAB character in a text file. In days gone by, on Unix
16system, dumb terminals, emacs, vi, etc… the tradition has been for a TAB character to mean,
17“move to the right until the current column is a multiple of 8”. Windows and Macintosh OSes do
18essential the same thing, except they use a multiple of 4. This is usually configurable by any cur-
20Point 3, what happens when you hit the <TAB> key. Some editors insert a TAB character (0x09)
21just like they would an ‘a’, ‘b’, or ‘c’. It then gets displayed on the screen according to Point 2,
22above. Some editors move your cursor over a certain number of spaces until you hit a multiple of
238 (or whatever). Some editors insert a number of SPACE (0x20) characters as defined in their
24configuration somewhere.
25Point 1 is the religious war. Points 2 and 3 are user interface and operability issues.
26Now that Jamie has helped us get our terms defined, let’s move on to our point.
27The big point to all this is that we all want the code we’re working on to look pretty, to line up, to
28be indented in a consistent manner. A SPACE character (0x20) is consistent, a TAB character
29(0x09) is not, taking on meanings of any multiple of 2, 4, or 8 columns. This becomes especially
30evident when TAB characters are used throughout a line, not just in the beginning.
31Below is a code fragment illustrating what I mean. This uses <TAB> characters, and the editor is
32set to display <TAB> characters on column lines of multiples of 4.
22This is all nice and lined up, now let’s look at the same code with our editor set to display the
23<TAB> character in a multiple of 2 columns:
24 void cm_task ( dword dummy )
25 {
26 static rex_sigs_type sigs; /* hold signals */
27 cm_cmd_s_type *cmd_ptr; /* command pointer */
28 cm_inband_cmd_s_type *inband_cmd_ptr; /* inband one */
29 cm_inband_cmd_info_s_type *cmd_info_ptr; /* info block */
30
31 cm_init(); /* initialize queues */
32
33 for( ;; ) /* Wait on REX, forever */
34 {
35 sigs = rex_wait( CM_RPT_TIMER_SIG
36 | CM_TIMER_SIG
37 | CM_RSSI_TIMER_SIG );
38
39 if( sigs & CM_RPT_TIMER_SIG ) /* call watchdog. */
40 {
41 cm_kick_dog();
42 }
43 } // for(;;)
44 }
45See how that’s no longer lined up all nice and pretty. The declaration of variables no longer line
46up. The comment lines neither. The flags in the rex_wait function don’t line up with the first
47flag anymore.
48You might be saying, well, if you only use <TAB> characters at the beginning of a line that’s not
49a problem. Quite true, but most people are going to use the <TAB> key to line things up past the
50beginning of a line instead of the <SPACE> key. This then puts a <TAB> character in the middle
52Further, when you go to print this code, many printers have their own meaning for the <TAB>
53character, sometimes 8 spaces, sometimes lining it up on columns that are multiples of 8.
54In short, the <TAB> character just means too many different things, depending on what applica-
55tion you’re using to view or print the code. We looked at many other style guidelines, since this
56is an issue that concerns most people with the fervor of the “Tastes Great! Less Filling” debate.
57The majority of these guides advocate using the <SPACE> character and not the <TAB> charac-
58ter.
1Hence we have mandated that there will be no, repeat no, <TAB> characters in the source code.
2You can setup your editor (MSVS++, vim, emacs, slickedit, etc…) so that when you hit the
3<TAB> key, it will indent it to the right indentation level, and use <SPACE> characters to do so.
2Most commercial IDEs supports configurable syntax expansion. Based on this document, KWC
3coding standard team has developed syntax expansion triggers for two popular IDEs among
4KWC developer: Visual Studio (Version 6.0) and Visual SlickEdit (Version 8.0).
5The idea is to link a “trigger” – a simple keystroke sequence with a macro (Visual Studio) or an
6alias (Visual SlickEdit) which expands predefined code blocks or file templates into the source
7code file being edited.
8Using auto syntax expansion not only speeds up coding process, but also enforces the coding
9standard. Section C.1 lists all the syntax expansion triggers being implemented at this point.
10Section C.2 and C.3 explain how to setup the syntax expansion in Visual Studio (Version 6.0)
12Please note a trigger ends with backslash (‘\’) in Visual Studio and space (‘ ‘) in Visual SlickEdit.
15 Comment blocks
Visual Studio Visual SlickEdit Expand to
“ssh\” “ssh ” C source (.c) file comment header (§3.2.1, §A.2)
“ffh\” “ffh ” C header (.h) file comment header (§3.1.2, §A.1)
“fch\” “fch ” C function comment header (§3.2.3, §A.1)
“bc\” “bc ” C-Style comment block (§5)
16 Function templates
Visual Studio Visual SlickEdit Expand to
“func\” “func ” C Function declaration template (§4.9)
“re\” “re ” C “return;” statement
17
18
20 Controlled block - if
Visual Studio Visual SlickEdit Expand to
“if\” “if ” C “if” block
“ife\” “ife ” C “if-else” block
“eli\” “eli ” C “else if” block
“el\” “el “ C “else” block
23 Preprocessor - #if
Visual Studio Visual SlickEdit Expand to
“3if\” “3if “ “#if - #endif” block
“3ife\” “3ife ” “#if - #else - #endif” block
“3ifd\” “3ifd “ “#ifdef - #endif” block
“3ifn\” “3ifn “ "#ifndef - #endif" block
“3e\” “3e “ "#else"
“3ei\” “3ei “ “#elif"
24
25
26
27 Preprocessor - #define
28 Preprocessor - others
Visual Studio Visual SlickEdit Expand to
“3i\” “3I “ #include <\^.h>
“3er\” “3er ” #error
“3p\” “3p “ #pragma
165. Close the dialog. Open a C file (.c or .h), type in “fo\”. It should be expanded into a for loop
17 block like this:
18 for ( ; ; )
19 {
20 }
6. Close the dialog by clicking OK. Open a C file (.c or .h) type in “fo ” (space after fo). It
11
2D.1 Description
3This document describes the robust function format we should use for our standard and higher
4level methods. It is a time tested and proven way to eliminate bugs early in the development
16would be translation methods used to convert a byte to its ASCII hex representation, or boolean
18
36D.2.2.1 FUNCTION
37Copy and paste the name of the function.
38D.2.2.2 DESCRIPTION
39Enter a description of the unique behavior of this function and provide information about any
40special cases.
41D.2.2.3 ARGUMENTS
42Copy and paste the arguments from the function declaration. Give a description of the purpose
43(eg: The string to be inserted ) of the argument followed by rules on valid input (eg: Must be
44Non-NULL and contain only ASCII characters and digits.)
11StatusCode_t), this will be very useful in determining how the method is expecting to use the
12parameter.
13
14• OWN Signifies that a pointer’s ownership (ownership = who needs to free the memory)
15 will change upon the successful return of a function – MUST be preceded by IN_ or OUT_.
16 See section Error! Reference source not found. for error returns. Note that having a pointer
17 change ownership is NOT recommended and should only be used in extreme cases.
18
19• IN Signifies that the parameter’s value is (or may be) used.
20• OUT Signifies that the parameter’s value will (or may) be set by the method.
21• IN_OUT Signifies that the variables value is (or may be) used, as well as the value will (or
22 may) be set.
23• IN_OWN Signifies that a pointer allocated by the caller changes ownership to the called
24 function; The calling function should immediately set any local references to the pointer to
25 NULL to avoid using a pointer owned.
26• OUT_OWN Signifies that a pointer allocated by the called function changes ownership
27 to the caller after a successful return.
28
29Note: The Called Function always OWNs the memory in an error case
30If the called function returns an ‘error status’ then it is the CALLED function’s responsibility to
31free all pointers modified by the IN_OWN or OUT_OWN keywords. It is Never the calling func-
32tion’s responsibility to free variables marked with the OWN keyword if the status code returned
5Cleanup.
8Primitive Variables
10Pointers
All Pointers Must be initialized to NULL. This allows us to check in the cleanup portion of the
11
12code for any non-NULL pointers and free them. If you free a pointer during the Functional Logic
13portion for any reason, ensure that you immediately set it to NULL to avoid freeing a free’d
14pointer.
19padding bytes so a bit by bit comparison of the entire structure in memory (commonly using the
20‘sizeof’ operator and memcmp) does not fail due to the commonly forgotten padding bytes. By
21getting into the habit of always using UICALLOC it makes the usage natural and does not rely
28Ex:
29int intarray[100] = {0}; struct mystruct = {0};
30
31(Both of these statements will zero the entire data allocated, not just the first item.)
12Primitive values should always be checked to be within proper bounds as defined by their pur-
13pose. For Example: in the case of an index into an array the primitive should be checked to be
14within the array boundaries. If the input is supposedly an enumeration check to make sure the
16D.2.4.8 Pointers
17‘IN’ and ‘IN OUT’ Pointers should be checked to be Non-NULL. If it is legal for an incoming
18pointer to be NULL please place a comment in the initialization section declaring that you’re in-
19tentionally not checking an input pointer for NULL and give the reason why.
23our C coding standard they claim that goto is never appropriate. Hopefully without bringing up a
24flame war . . . they’re wrong . As you shall see there are cases where goto is appropriate and
29and program flow is more natural to follow. This can only be accomplished by having one (and
31
5modifying your function and ends up adding code in between the free and the new allocation this
6will stop them from accidentally using an already free’d value. As well it protects against the
7situation where you may have a double free when it is checked for NULL and free’d again in the
8cleanup section.
9It is also acceptable to assign the pointer to NULL on the same line that you free’d the pointer- to
10further enforce the fact that it is an atomic operation. Ex:
11 free ( p ); /* This is ok */
12 p = NULL;
13-or -
14 free( p ); p = NULL; /* This is also ok */
15
20(1) If the goto success: was not there, in the future if someone added additional code after the ‘if-
21 else if’ statement, processing if 3 == *B for example, they would have to go back, read, and
22 understand your code in order to realize that you intended to finish the function logic and ter-
23 minate in the success case. Reading and understanding seemingly unrelated code is a time
24 consuming and error prone process that should be avoided.
25(2) As well if they added an additional Success Label (perhaps to do some special processing
26 such as output a Cait debug string) under your Success label they would have to once again
27 read and understand your code in order to realize they needed to add a ‘goto Cleanup:’ to
28 avoid falling through to their success case.
33able to have several error labels which all branch to the main error label. Note that in an error
34case you MUST free all pointers modified with the OWN keyword in the Error section!
1is valid; if you are passing back an index into a buffer, assert the index is within the range of the
2buffer. This helps to catch mistakes made during the initial creation of the method, as well as
4D.2.8 Cleanup
5All cleanup (excluding freeing of OWN’d variables in an error case) should be done at the
6Cleanup label. All Non-Null pointers (allocated in this function) should be freed. Note it is ac-
7ceptable not to set the pointers to NULL here after freeing them since Cleanup should always be
Bit(s)* Description N
29-31 Reserved for Future use 8
21-28 Group Code (eg: SG_MESSAGING) 256
12-20 Sub-Group Code (eg: SB_ MESSAGING_MMS) 512
1-11 Specific Sub Codes 2048
0 Status Type (1 indicates successful status, 0 indicates a failed (unsuccessful) 2
status)
5* Bits are numbered with 31 being the most significant bit to 0 being the least significant bit
12Sub-Group codes are meant to categorize status codes at a finer, more module specific, level.
13Under the Widgets Group some potential sub groups would be text, picture, and forms. Under the
14Messaging Group some potential subgroups would be Message Creation, Message Viwing, Mes-
15sage Sending, Message processing, etc. Sub-Group codes are prefixed with SB followed by the
16name of the parent group. For the Text Widget, who is a member of the widget group, the format
7Only a portion of the string was able to be appended before the data buffer ran out of space.
8None of the string was able to be appended since the buffer was already at capacity. Or, the ap-
12since this is an acceptable status this status code could have the StatusType set to SUCCESS)
16CESS)
17If the StringAppend method failed due to an out of memory condition it could could return
18SCE_OUT_OF_MEMORY. If the text passed in was null thus there were no characters to ap-
19pend it could return SCE_UNEXPECTED_NULL_PARAMETER. If it failed because the text
21due to an undefined internal append error (not allowed to append empty strings, certain charac-