EDK II C Coding Standards Specification
Version 2.1
30 October 2015
Contents
EDK II C Coding Standards Specification i
2.2 Principles for Software Maintenance 6
2.2.1 Understand the problem before you fix it. 6
2.2.2 Understand the program, not just the problem. 6
2.2.3 Fix the symptom AND the underlying problem. 7
2.2.4 Change the code only for good reason. 7
2.2.5 Do not debug by superstition. 7
2.2.6 Don’t blame everyone else’s code. 7
2.2.7 Don’t use source control to debug problems. 7
2.2.9 Look for similar errors. 7
2.2.10 Fix the code AND the comments. 7
2.2.11 Fix the comments AND the documentation. 8
2.3 Additional Recommendations 8
3.2.1 Formatting: General Rules 11
3.2.2 Formatting: Vertical spacing 11
3.2.3 Formatting: Horizontal spacing 11
3.2.4 Formatting: Predicate Expressions 12
3.3.1 Files: Horizontal Spacing 12
3.3.4 Code Files: Vertical Spacing 14
3.4.1 Documentation: Commenting 14
4.1.1 Identifiers that are always reserved 16
4.1.2 Common Opposites in Variable Names 16
4.2.1 There is no limit to file name lengths. 19
4.2.2 Spaces in file and directory names are NOT permitted. 20
4.2.3 Never start file names with numbers. 20
4.2.4 Non-standard characters shall not occur in file names. 20
4.3.1 Identifiers shall not rely on the significance of more than 31 characters. 20
4.3.2 Always make identifier names that are visually distinguishable. 20
4.3.4 Function and Data Names 21
4.4 Global & Module Variables 23
4.4.1 Recommendations for Global and Module Variables 24
4.5.1 Names shall be used consistently within the same type. 24
4.5.2 No identifier in one name space may be reused as an identifier in another name space 24
4.5.3 A typedef name shall be a unique identifier. 25
4.5.4 A tag name shall be unique. 25
4.5.5 Prefix module-scope identifiers for cleaner namespaces. 25
5.1.1 Lines shall be 120 columns, or less 26
5.1.2 Do not use tab characters 26
5.1.3 Files may only contain the ASCII characters 0x0A, 0x0D, and 0x20 through 0x7E 26
5.1.4 Only escape sequences defined in the ISO C standard shall be used in string literals. 26
5.1.5 Octal constants (Base 8) shall not be used. 27
5.1.6 Only use CRLF (Carriage Return Line Feed) line endings. 27
5.1.7 All files must end with CRLF 27
5.1.8 Trigraphs shall not be used 27
5.1.9 In-line assembler shall not be used 27
5.1.10 Do not use #pragma, except for #pragma pack (#). 27
5.3.1 All C include file names shall contain only one extension and it must be .h. 33
5.3.2 Every include file shall have a unique name. 33
5.3.3 Include files shall not consist mainly of include directives. 34
5.3.4 Include files may include only those headers that it directly depends upon. 34
5.3.5 All include file contents must be protected by a #include guard. 34
5.3.6 Include files shall contain only public or only private data. 34
5.3.7 Include files shall not generate code or define data variables. 34
5.5 Preprocessor Directives 40
5.6.3 Structure Declaration 46
5.7.1 Function Definition Layout 48
5.7.2 Predicate Expressions 51
5.7.3 Flow Control Statements 54
5.7.4 Structure Definitions 56
5.8 Error Handling and ASSERT 57
6.1.2 Interfaces or Protocols 59
6.2.2 Avoid banners or other decoration around blocks of comments. 59
6.2.3 Avoid comments where the opening comment characters are alone on a line. 59
6.2.4 Do not include jokes or obtuse references in comments. 60
6.3.1 Do not repeat the code or explain it in a comment. 60
6.3.2 Do not leave markers in the code. 60
6.3.3 Sections of code shall not be “commented out”. 60
6.3.4 Do not comment out, or otherwise disable, previous revisions of the code. 60
6.3.5 Do not use the character sequence “/*” within a comment. 61
6.4.1 Comment function declarations if public, or implementations if private and not declared. 61
6.4.2 Comment complicated, tricky, or sensitive pieces of code. 61
6.4.3 Comment higher-level concepts in the code. 61
6.4.4 Comment data structure declarations and #define statements. 61
6.8 Special Documentation Blocks 64
6.9 Putting Documentation after Members 65
6.10.1 @example <file-name> 66
6.10.3 @attention { attention text } 66
6.10.4 @param[in,out] <parameter-name> { parameter description } 66
6.10.5 @post { description of a postcondition } 66
6.10.6 @pre { description of a precondition } 66
6.10.7 @retval <return value> { description } 66
6.10.8 @return { description of what is returned } 66
6.10.11 @test { paragraph describing a test case } 67
6.10.12 @todo { paragraph describing what is to be done } 67
APPENDIX B Reserved Identifiers 76
APPENDIX C Optimization and Performance 83
THIS SPECIFICATION IS PROVIDED "AS IS" WITH NO WARRANTIES WHATSOEVER, INCLUDING ANY WARRANTY OF MERCHANTABILITY, NONINFRINGEMENT, FITNESS FOR ANY PARTICULAR PURPOSE, OR ANY WARRANTY OTHERWISE ARISING OUT OF ANY PROPOSAL, SPECIFICATION OR SAMPLE. Except for a limited copyright license to copy this specification for internal use only, no license, express or implied, by estoppel or otherwise, to any intellectual property rights is granted herein.
Intel disclaims all liability, including liability for infringement of any proprietary rights, relating to implementation of information in this specification. Intel does not warrant or represent that such implementation(s) will not infringe such rights.
Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them.
Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries.
* Other names and brands may be claimed as the property of others.
Copyright 2006-2015, Intel Corporation
Revision History
Revision | Revision History | Date |
0.0.1 | First swag. | 6/23/00 |
0.0.2 | Included feedback from team. | 8/3/00 |
0.3 | Add comments. | 8/10/00 |
0.3001 | Pre-vacation update, need to sync with new numbering process. | 9/11/00 |
0.31 | Incorporated Sync 1 learnings. | 12/12/00 |
0.32 | Completed TAT ARs. | 6/8/01 |
0.33 | Added goto rules. | 8/16/01 |
0.34 | Updated to match driver and Runtime Lib. | 11/15/01 |
0.9 | Updated to Intel® Platform Innovation Framework for EFI. |
Added checklist appendix. | 1/8/04 |
| 0.91 | Completed editing and formatting pass. | 3/3/04 | | 0.92 | Updated the structure declaration rules: Added section 4.8 and modified the checklist in Appendix A. | 4/8/04 | | 0.93 | Added some minor clarifications in section 3.1, 4.5, 7.1, and 10. | 9/14/04 | | 0.94 | Revised to accommodate Doxygen style commenting standards | 3/1/06 | | 0.50 | Change to new numbering scheme. Incorporate Review Comments. Editing and formatting. | 4/21/06 | | 0.51 | Changed to EDK II. | 7/13/06 | | 0.52 | Update rules to clarify areas of misinterpretation.
Add copyright formatting rules. | 2/09/2010 |
| 0.60 | Re-organize document and update to current rules. | 2/15/2010 | | 0.70 | Release for Review | 3/1/2010 | | 0.95 | Review comments incorporated, Release to Tech Pubs for Finalization | 3/10/2010 | | 1.00 | First full release | 3/15/2010 | | 1.01 | Restructure into book format. | 12/08/2011 | | 1.02 | Incorporate suggestions and trackers | 3/19/2012 | | | Release For Review | 4/2/2012 | | | Release | 4/16/2012 | | 1.03 | Update and incorporate requests and bug fixes. Remove “Intel Confidential” classification. | 9/11/2014 | | 1.50 | Release for Review | 9/26/2014 | | 1.80 | Incorporate US Review Comments | 10/10/2014 | | 1.85 | Incorporate PRC Review Comments | 10/24/2014 | | | Release for Extended US & PRC Review | 10/28/2014 | | 2.0 | Release | 11/14/2014 | | 2.1 | DRAFT for REFORMAT | 10/30/2015 | | | | |
</span></span></span>
Introduction
</span></span>Abstract
This specification establishes a set of rules to:
Establish uniformity of style.
Set minimum information content requirements.
Allow all programmers to easily understand the code.
Facilitate support tasks by establishing uniform conventions.
Ease documentation efforts by embedding the design documentation in the code.
Reduce customer and new employee learning curves by providing accurate code documentation and uniform style.
These rules apply to all code developed for inclusion in the EDK II code base, and are intended as an enabling philosophy. All changes or additions from this point on shall conform to this specification. Pre-existing code does not need to be updated for the sole purpose of conforming to this specification. As conforming updates are made, the developer may update other content within the modified file to bring it within compliance with this specification. Code originally developed for other environments that has been ported to, or modified for, the EDK II environment, is not obligated to conform. However, any new code added to the ported code must conform.
This specification addresses the chronic problem of providing accurate documentation of the code base by embedding the documentation within the code. While this does not guarantee that the documentation will be kept up to date, it significantly increases the chances. A document generation system, Doxygen, then produce formatted documentation by extracting information from specially formatted comment blocks and the syntactic elements of the code.
This specification presents protocol standards that will ensure that the contractual relationship between APIs and their callers is clear and well maintained.
This specification describes standard practices designed to eliminate or mitigate pitfalls inherent in the C language.
In recognition that a coding standard of this size can be a bit daunting, a concise reference to the standard’s key elements is available in "Quick Reference”.
</span></span>Rationale
Software engineering is much more than writing code that will work one time. Software engineering entails writing code that:
Meets project requirements.
Is testable.
Can be maintained by the author or by others that have varying degrees of experience and familiarity with the code.
Minimizes the learning curve for programmers new to the product. (Our customers)
We use the C programming language because of its simplicity, flexibility, and wide support. On the downside in that each developer’s C code could (conceivably) be constructed in totally different and inconsistent ways. This lack of uniformity makes understanding and maintaining the code very difficult.
Uniformity is the key theme of these rules. You may disagree with some of our decisions. Nevertheless, we ask that you commit to conforming to standards of this specification. Also, there are pitfalls inherent in the C language that this style guide may help you to avoid. The goal of this document is making you, and those who follow you, more productive.
Some of the strict rules for protocol and driver construction may seem overly onerous. Don’t panic — there is a method to our madness — we intend to construct wizards to aid in the construction of protocol include files and device driver templates. The resulting consistency will help prevent name collision and require much less rote memory (or code surfing) to remember the names of protocol declarations or GUID definitions.
Good software engineers think about maintaining a consistent and uniform coding style. Having a set of rules to follow allows them to spend time solving actual problems and less time thinking about style. Junior software engineers may not see the benefits, but now is a good time for them to start thinking about what it will take to maintain their code. Junior software engineers will also benefit by being able to understand other people’s code much more easily because the code will be written in a consistent manner. Consistency and uniformity enable productivity.
In conclusion, it’s uniformity, uniformity, uniformity. With that said, this document is not intended to be dogma. However, violating a rule is contingent on valid reasons for the violation, and the approval of the various stakeholders involved. It is not something to venture into lightly and is not recommended.
</span></span></span> Scope
This specification describes stylistic conventions and requirements as they apply to writing C code for inclusion within the EDK II code base. Its bulk is intended to provide rationale and disambiguating detail for each rule and requirement. The rules are also presented in summary form for quick reference. Rationale and detail for each of the rules is then presented in subsequent sections.
The majority of code produced for EDK II must support multiple compilers and be able to be retargeted to multiple processor and system architectures. This requires coding practices to conform to the “lowest common denominator” of the supported tools, processor, and system architectures.
The C dialect we use is ISO/IEC 9899:199409, or C95, with some elements from C99. If you are not familiar with this dialect, refer to Harbison and Steele's C: A Reference Manual. This is the language dialect held in common with all of the compilers supported by EDK II.
- There are some significant differences between ANSI C (C89) and the dialect recognized by compilers supported by EDK II (C95). These differences primarily revolve around use of the external storage class and the elimination of implicit types and storage classes.
The use of compiler-specific language extensions is very strongly discouraged.
Topics covered in this coding standard include:
File structure and formats
C language rules and guidelines
Naming Conventions
Documentation
Commenting rules
Doxygen
These guidelines represent an attempt make you aware of your actions, because those actions affect the future readers and maintainers of the code you produce.
Pre-existing code ported to the EDK II environment does not have to conform to this specification. New code which is added to, or which accompanies, the ported code must conform.
This specification considers the core firmware, applications, and individual UEFI drivers as distinct and separate units. This is because UEFI drivers, like applications, are not linked to the main body of code and do not expose their internal namespaces to other components of the firmware system.
</span></span>References
MISRA-C: 2004 Guidelines for the use of the C language in critical systems, Tyler Doering http://www.misra-c.com*/ Guidelines for the Use of the C Language in Critical Systems*, ISBN 978-1-906400-10-1 (paperback), ISBN 978-1-906400-11-8 (PDF), March 2013.
Universal Principles of Design by William Lidwell, Kritina Holden, and Jill Butler. ISBN 1-59253-007-9.
C: A Reference Manual by Samuel P. Harbison III and Guy L. Steele Jr. ISBN 0-13-089592x.
Enough Rope to Shoot Yourself in the Foot by Allen I. Holub. ISBN 0-07-029689-8.
Code Complete by Steven C. McConnell. ISBN 1-55615-484-4.
The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie. ISBN 0-13-110362-8.
ISO/IEC 9899: 1990, Programming Languages - C. This specifies ANSI C.
ISO/IEC 9899: 199409, Programming Languages - C. This specifies C95.
ISO/IEC 9899: 1999; Cor-3, Programming Languages - C. This specifies C99.
Writing Solid Code by Steve Maguire. ISBN 1-55615-551-4.
EFI Application Toolkit Project Engineering Conventions. 10/4/1999.
ISO/IEC 6592: 2000, Information Technology - Guidelines for the Documentation of Computer-based Application Systems.
ISO/IEC 18019: 2004, Software and System Engineering – Guidelines for the Design and Preparation of User Documentation for Application Software.
Indian Hill C Style and Coding Standard by L.W. Cannon, R.A. Elliott, L.W. Kirchhoff, J.H. Miller, J.M. Milner, R.W. Mitze, E.P. Schan, N.O. Whittington, Bell Labs; Henry Spencer, Zoology Computer Systems, University of Toronto; David Keppel, EECS, UC Berkeley CS&E, University of Washington; Mark Brader, SoftQuad Incorporated, Toronto. 6/25/1990.
Doxygen manual Version 1.4.6-NO
Doxygen Primer by Daryl McDaniel, IBM 2002; Updated for Intel Corporation 1/2006
UEFI Specification, www.uefi.org
Beyond Bios,
</span></span>Glossary
ANSI
American National Standards Institute
C
The generic name for the C Programming Language. Originally finalized as an ANSI standard in 1989 (‘C89’) and updated in 1999 (‘C99’). Subsequently adopted by the ISO (ISO/IEC 9899:1990), which has replaced the ANSI standard, even in the US.
CVS
Concurrent Versioning System
EFI
Extensible Firmware Interface
ISO
International Standards Organization
SVN
The Subversion revision management system.
Tab Stop
EDK II uses space characters instead of Horizontal Tab characters. If the left-most column is column 1, then every odd numbered column is a Tab Stop. Code elements are aligned at Tab Stops.
</span></span>
Guiding Principles
This chapter discusses the principles of high-quality software. It is likely that your design will not be able to achieve all of these goals; if it does, your design is very good indeed. Note that some of these design goals contradict other design goals. Contradiction is part of the challenge of doing a good design.
Maintainability of software is of such importance that those principles are expanded separately in “Principles for Software Maintenance”.
</span></span>Software Design
The following is an alphabetical list of software design principles:
Accessibility
This entails designing objects and environments to be usable, with no modification, by the greatest number of people as possible, including people with varying educational and social backgrounds, as well as those with motor or sensory challenges.
Alignment
Elements within a design should be aligned with one or more other elements. Alignment of related or like elements within a design reduces the perception of disorder and promotes understanding.
Chunking.
Chunking groups units of information into a small number of units (maximum of four plus or minus one) to help the efficient processing of information by short-term memory, as well as to accommodate its limits.
Confirmation.
This is a technique used for critical actions, inputs, or commands. Confirmations are primarily used to prevent unintended actions. Minimize errors in critical or irreversible operations with confirmations. If you overuse confirmations, expect that they will be ignored Avoid overusing confirmations to ensure that they remain unexpected and uncommon; otherwise, they may be ignored. Use a two-step operation for hardware confirmations and dialogs for software confirmations.
Consistency.
Express similar parts or concepts in similar ways to make a system to improve usability and learnability. Apply consistency to design and coding style, as well as user interfaces. Do not apply consistency to the point of compromising clarity or usability.
Maintainability
Design for the maintenance programmer or sustaining engineer for maintainability, or ease of maintenance. The design of the system should be self-explanatory.
Extensibility
Extensibility entails enhancing a system without violating the underlying structure. The most likely changes should cause the system the least trauma. For example, you know the BIOS is responsible for booting the system, so adding a new type of boot device should not cause trauma to the system. Be careful about the assumptions you make.
Forgiveness.
Design to help users avoid errors and reduce the negative consequences of errors any errors made. Recommended methods for achieving design forgiveness include affordances, reversibility of actions, and safety nets. Effectively designing for forgiveness results in a design needing minimal confirmations, warnings, and help.
High fan-in
Sharing a high number of routines that call a given routine produces high fan-in. Sharing entails designing a system to make good use of utility routines at the lower levels.
Horror Vacui
This is a Latin phrase for “fear of emptiness”, which is the desire to fill empty spaces with information or objects. Research shows that as horror vacui increases, perceived value decreases. In programming, lines consisting solely of comment characters, with no actual comment, are good examples of horror vacui.
Intellectual manageability.
Intellectual manageability is a primary goal in any system. It is essential to the overall system integrity and affects how easily programmers can initially build a system as well as maintain it later.
Interference Effects.
When two or more perceptual (or cognitive) processes are in conflict, the competing mental processes slow down mental processing or make mental processing less accurate. Examples of this include violations of convention (a red OK light), information conflicts (a color name, GREEN, in a different color), and incorrect use of opposites.
Leanness
Design the system so that it has no extra parts, i.e. “lean”. If you add extra code, remember that it needs to be developed, reviewed, tested, maintained, understood, and taken into account when the code is modified. Also, future versions of the code may have to be backward compatible with the extra code.
Low complexity
Low complexity is part of intellectual manageability.
Minimal connectedness
Design so that you keep connections among subprograms to a minimum. This minimizes work during integration, testing, and maintenance. Use industry standards whenever possible. Make sure you are not reinventing something that already exists.
Minimize code size.
Unlike many software engineering projects, EDK II firmware is targeted to be stored in a device that represents a tangible cost to the system. Thus, the minimization of code size is important to reduce the overall cost of a system.
Portability
Design the system so that it is easily moved to another environment. With EDK II, making sure the code will run on IA32, X64 and Intel® Itanium® processors (IPF) is an example of portability.
Reusability
Design the system so that pieces of it can be reused in other systems. In EDK II, reusability also means designing code so that it can be used in various classes of platforms from embedded systems to massively parallel computers.
Standard techniques.
Greater reliance on unique or exotic pieces makes a system harder to understand, and more intimidating for someone trying to understand it the first time. Using standardized, common approaches should be to give the whole system a familiar feeling. This standardization is one of the primary goals of this document.
Stratified design
In order to view the system at any single level and get a consistent view of it, you should attempt to keep the levels of decomposition layered. The OSI multi-layer-networking model is an example of stratified design.
</span></span></span></span></span></span></span>Principles for Software Maintenance
Understand the problem before you fix it.
The best way to ruin a code base is to attempt to fix problems without a clear understanding of the problem itself. If your fix is out of context, the next fix in the routine will be four times more complicated. Triangulate the error with cases that should and should not cause the error. Keep at it until you understand the error.
Understand the program, not just the problem.
Understanding the context in which a problem occurs will increase your likelihood of solving the problem completely.
Fix the symptom AND the underlying problem.
Fix the symptom, but your focus should be on fixing the underlying problem. Without thoroughly understanding the problem, you will not fix the code. You will also feel very uncomfortable when a peer reviews your fix before you check it into the source base.
Change the code only for good reason.
Do not change code at random until it seems to work; that isn’t effective. If you do this you are not learning anything and are just goofing around. You should have confidence that a change will work before making a change. Being wrong about a change should be rare and cause personal reevaluation.
Do not debug by superstition.
Don’t blame every problem on the computer, bad data, or the effects of a full moon. You wrote the program; take responsibility for it.
Don’t blame everyone else’s code.
It is human nature to trust the code that you wrote and understand, and to distrust all other code. You must resist this tendency and root cause the problem systematically.
Don’t use source control to debug problems.
You don’t debug by randomly trying previous versions of code. You can use previous versions as a single test of your triangulated test cases. Bugs are not always introduced by changes. Bugs can lie dormant in a code base for long periods of time. By blindly rolling back changes, you could just be hiding a bug, versus fixing one.
Check your fix.
Run the triangulated test cases against your code. Have another set of eyes look at your change, preferably someone who is experienced in the code.
Look for similar errors.
Errors tend to occur in groups, so check to make sure a similar mistake was not made in other parts of the code.
Fix the code AND the comments.
When you have correct code but incorrect comments, you will confuse the next person in the code. Remember, programming is a team sport.
Fix the comments AND the documentation.
The next person to make a large change to code will thank you and might even not camp out in your cube for a week. This has been simplified in EDK II by embedding the documentation within the comments.
Additional Recommendations
If you have trouble debugging without violating these rules, please ask for help.
Learn to debug by debugging with someone who is good at it. There is (approximately) a 20-to-1 difference in the time it takes an experienced programmer to find the same set of errors as an inexperienced programmer.
Try to not focus only on the bug, but on the process and techniques the experienced programmer uses to find bugs.
When working with a more experienced debugger, your goal should be to improve your debugging skills.
If you rely too heavily on the debugging skills of others, your own expertise suffers.
</span>
</span>Quick Reference
Naming
Names must clearly represent the purpose of the named object. See "General Naming Rules".
Do not use names that are very similar to existing concepts, such as ‘event’. See "General Naming Rules".
Do not use the names of symbols declared in standard header files as internal symbols. See "Function and Data Names".
Overloading function or type names is not allowed. "Name Space Rules".
Use the correct opposites when naming. See "Common Opposites in Variable Names".
Use standard abbreviations only. See "Abbreviation Usage".
Use industry standard acronyms only. See "Acronym Usage".
Any nonstandard abbreviation or acronym must be defined in the file header of any file using the abbreviation or acronym. See "Abbreviation Usage" & "Glossary".
There is no limit to name lengths. A length of 10 to 30 characters is ", recommended. See “File Names " &"Identifiers that are always reserved".
File names must not start with numbers. See “File Names".
Each include file name must be unique. See "Include Files”.
File, function, variable, enumeration, and data structure elements must have names like the following:
EachWordIsDistinctEvenAcronymsLikeAcpi. See "Identifiers".
Don’t capitalize all letters in acronyms. MyPCIAddress is hard to read, compared to MyPciAddress, especially if acronyms are mixed with numbers, like My870PCIBus0BDF. See "Acronym Usage”.
Acronyms in comments and documentation shall follow English rules and be capitalized. See "Acronym Usage”.
Functional macros, #defines, and typedefs must have names like: EACH_WORD_IS_DISTINCT_EVEN_ACRONYMS_LIKE_ACPI See "Type and Macro Names".
Hungarian naming is not allowed. See "Hungarian Prefixes”.
Global data names must be prefaced with a ‘g.’ Example: gMyGuid. See "Global & Module Variables”.
Module global data names must be prefaced with an ‘m.’ Example: mMyGuid. See "Global & Module Variables”.
Formatting
Formatting: General Rules
Tab characters are not allowed. See "General Rules”.
All indentation (tabs) is two spaces. See "General Rules”.
Formatting: Vertical spacing
Use blank lines and comments to group blocks of related code. See "Vertical Spacing”.
Never put more than one statement per line. See "Vertical Spacing”.
Never put the code and conditional on one line. See "Vertical Spacing
Never put more than one declaration per line. UINT8 MyData1, MyData2; is illegal. See "Vertical Spacing”.
Always put open braces ‘{’ on their own line for functions or multi-line predicate expressions. All other uses put the brace following the conditional. See "Vertical Spacing”.
Always put close braces ‘}’ on their own line, indented to match the first line of the construct. Exceptions are else, else if, and do-while code. See "Vertical Spacing”.
Formatting: Horizontal spacing
Always put space before and after binary operators. See "Horizontal Spacing".
Never put space between unary operators and the operand. See "Horizontal Spacing".
Always put space after ‘,’, or ‘;’ if more code follows. See "Horizontal Spacing".
Always put space before a ‘(’ except for “((. See "Horizontal Spacing".
Always put space before a ‘{’ if it is not on its own line. See "Horizontal Spacing".
Never put spaces around ‘.’ or ‘->’ operators. See "Horizontal Spacing".
Never put a space between array operands and ‘[.’ See "Horizontal Spacing".
Always Line up continued lines with the element being continued. See "Horizontal Spacing".
Formatting: Predicate Expressions
Always use parentheses rather than relying on "Horizontal Spacing" (above) operator precedence. "Predicate Expressions".
Booleans do not need to be compared with TRUE or FALSE. See "Predicate Expressions".
Pointers must be explicitly compared to NULL. See "Predicate Expressions".
Numbers must be explicitly compared to another number. See "Predicate Expressions".
</span></span></span> Files: General Rules
Do not use tabs, only use Spaces. "General Rules".
Unless explicitly stated otherwise, spaces (white space) may be one or more space characters long. See "General Rules".
Files may only contain the ASCII characters 0x0A, 0x0D, and 0x20 through 0x7E, inclusive. See "General Rules".
Do not produce lines that exceed 120 columns in your source files. See "General Rules".
New files shall not use #pragma except for #pragma pack(#). See "General Rules".
Ported files may retain pre-existing #pragmas. See "General Rules".
Ported files may contain #pragmas to disable prevalent warning messages.
All lines must end with CRLF (Carriage Return Line Feed); 0x0D followed by 0x0A.
All files must end with CRLF. See "General Rules".
Every new file must begin with a "File Heading" comment block. See "File Heading".
Files: Horizontal Spacing
Always put space before and after binary operators. See “Horizontal Spacing".
Do not put space between unary operators and their object. See “Horizontal Spacing".
Horizontal spacing for multi-line function calls should line up one or two tab stops after the beginning of the function name. See “Horizontal Spacing".
Always put space after commas or semicolons that separate items. See "Horizontal Spacing".
Always put space before an open parenthesis, except for macro definitions. See “Horizontal Spacing".
Put space before an open brace if it is not on its own line. See “Horizontal Spacing".
Do not put space around the structure member, ‘.’, and pointer, ‘->’, operators. See “Horizontal Spacing".
Do not put space before the open brackets, ‘[‘ of array subscripts. See “Horizontal Spacing".
Align a continuation line with the part of the line that it continues. See “Horizontal Spacing".
Use parentheses instead of relying upon knowledge of C precedence ordering. See “Horizontal Spacing".
Include Files
- Every header file must have a ‘#ifndef FILE_NAME_H_’ and ‘#endif’ guard surrounding all code. See “Include Files".
The #ifndef must be the first line of code following the file header comment.
The #endif’ must appear alone on the last line in the file.
All C include files shall use the same extension and it shall be .h. See “Include Files".
Include statements shall not contain absolute paths or paths that contain ‘..’. See "#include"
Functional macros are discouraged except for includes, debug, CR, and linked lists. See "Macros”.
Macros should be defined with the maximum use of parentheses to remove any possible ambiguity. See "Macros”.
Include files must contain either public or private data, not both. See “Include Files".
Include files must not contain code generating statements. See “Include Files".
Every parameter must have the proper IN, OUT, OPTIONAL, etc., modifiers. See "Function Definition Layout".
Only use UEFI data types. Use of standard C data types is prohibited. See "Common Data Types”.
Code Files
Only use UEFI data types. Use of standard C data types is prohibited. See "Common Data Types”.
Code files should not contain #define and typedef statements.
Do not use inline assembler in the source files. See "General Rules".
Function definitions, as well as if, for, while, and switch statements, must follow strict rules. See "Function Definition Layout", "Flow Control Statements, and “Introducing Doxygen".
Enumerated types must end with a maximum element. See "Enumerated Types".
Enumerated types should begin with a minimum element.
Structures are always defined with a typedef format. See "Structure Definitions".
The open and closing braces of a function definition are in column one and on their own lines. See "Function Definition Layout".
Code Files: Vertical Spacing
There shall be only one statement per line. See "Vertical Spacing".
Open braces, ‘{‘, shall be on the same line as the closing parenthesis, ‘)’, of one-line predicate expressions. See "Vertical Spacing".
Open braces, ‘{‘, shall be on a line by themselves and aligned with the first character of the associated flow control statement when following a multi-line predicate expression. See "Vertical Spacing".
Close braces, ‘}’, always go at the beginning of the last line of the body. See "Vertical Spacing".
A close brace may share a line with the else {, else if () {, and do-while constructs. See "Vertical Spacing".
Each sub-expression of a complex predicate expression must be on a separate line. See "Vertical Spacing".
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>2.3 Documentation
Documentation: Commenting
Comments must explain why the code does what it does. See "Comments".
Every file must have a properly formatted file header. See "File Heading".
Every function and functional macro must have a correct function header in both the source and include files. See "Macros" & "Function Headings".
Documentation: Internal comments
Local comments must use the C++ comment style, ‘//’. See "Internal Comments".
Local comments must have a blank line before the comment block. See "Internal Comments".
Comments must be indented to match the code. See "Internal Comments".
If a comment applies to more than one block of code, there should be a blank line after the comment. See "Internal Comments".
If a comment applies to a single block of code, there should not be a blank line separating the comment from the code. See "Internal Comments".
Documentation: What not to comment
- No comment markers are allowed in code, including:
BUGBUG
Your name
Your initials
Special markers, such as FIX_THIS, TEST . See "What NOT to Comment”.
- Use your bug tracking system to track bugs instead of markers within the code. If you really must mark the code, use Doxygen’s @bug or @todo commands. See "What NOT to Comment”.
</span>Doxygen
Doxygen comments are used to document global and file-scope elements. See "Global Comments".
C-style comment blocks are of the form:
/** Brief Description. * … More text … */
C++ style comment blocks begin with ///.
Comments precede the semantic element they document. See "Special Documentation Blocks”.
The special form, ///< …, allows documentation to be after the documented element. See"Putting Documentation after Members".
Comment blocks automatically start with a brief description and end at the first period. See "Special Documentation Blocks" .
The most frequently used Doxygen commands are: ( See "Special Commands").
@file [<name>]
@param[in,out] <parameter name> { parameter description }
@retval <return value> { description }
@sa { references }
@test { description of a test case }</span>
</span>
Naming Conventions
</span></span></span></span>General Naming Rules
Use good naming practice when declaring variable names.
Studies show that programs with names averaging 10 to 16 characters are the easiest to debug. The name length is just a guideline; the most important thing is that the name conveys a clear meaning of what it represents.
Do not overload commonly used terms.
For example, EFI has an event model, so don’t call some abstraction that you define an Event. People will get confused. Make sure someone reading the code can tell what you are talking about.
Each word or concept must start with a capital letter and be followed by lower-case letters.
The intent is for names to be consistent and easily readable. Each word in a compound name should be visually distinct.
</span>Identifiers that are always reserved
Identifiers beginning with an underscore are always reserved.
Define them only in the special ways allowed elsewhere in this document.
Identifiers that are defined in the Standard C and POSIX libraries are always reserved.
This includes macros, typedefs, variables, and functions, whether with external linkage or file scope. The only exception is with modules that are mutually exclusive with these libraries. These reserved identifiers are listed in "Reserved Identifiers" on page 78 and reserved keywords are listed in "Reserved Keywords" on page 24.
</span></span></span></span>Common Opposites in Variable Names
Use the correct opposites when declaring names.
Table 2 - 1. Common Opposites
• add / remove |
• insert / delete
• increment / decrement
• lock / unlock
• old / new
• source / destination | • begin / end
• first / last
• put / get
• min / max
• open / close
• source / target | • create / destroy
• get / release
• up / down
• next / previous
• show / hide
• start / stop |
</span></span> </span>Abbreviation Usage
The use of abbreviations shall be regulated.
This document describes a common set of abbreviations that can be freely used. If you must make up abbreviations, remember the name is most important to the reader of the code, not the writer.
New abbreviations must be documented in the header of each using file.
Any abbreviation used, which is not documented in this specification, or in the UEFI Specification shall be placed into a Glossary section of the File header as specified in See "File Heading".
Do not define a new abbreviation to replace an abbreviation that is already defined in this document. For example, do not define No to mean Number, because Num is the supported abbreviation.
"EFI Supported Abbreviations" below lists the abbreviations that are standardized by this document and do not require a defining comment.
</span>Table 2 - 2. EFI Supported Abbreviations
Abbreviation | Description |
Ptr | Pointer |
Str | Unicode string |
Ascii | ASCII string |
Len | Length |
Arg | Argument |
Max | Maximum |
Min | Minimum |
Char | Character |
Num | Number |
Temp | Temporary |
Src | Source |
Dst | Destination |
BS | EFI Boot Services Table |
RT | EFI Runtime Table |
ST | EFI System Table |
Tpl | EFI Task Priority Level |
Powers of 2 and 10
You are encouraged to use the IEC international abbreviations for powers of 2 (KiB for 2^10, MiB for 2^20, GiB for 2^30, etc.) rather than the old KB, MB, and GB, which IEC now reserves for powers of 10 (10^3, 10^6, 10^9). Given that many readers of the code may not have made the conversion to add the ‘i’, do not use KB, MB, and GB for powers of 10. Instead, use e.g. “2*10^6 bytes” instead of 2MB to avoid confusion. Note that GiB is derived from the G in ‘Giga’, the ‘i’ in binary, and the B in ‘Byte’.
</span></span></span></span>Acronym Usage
The use of acronyms shall be limited.
Please remember the golden rule: Code for the person who will have to read and maintain your code. Making up your own vocabulary to describe your module can lead to lots of confusion.
Created Acronyms must be fully defined.
If you must create acronyms, they must be fully defined in the documentation
Translation tables are required for each module using a created acronym
Each module that uses the acronym must contain a translation table comment in the file header. This definition is required so that others can understand your names and comments.
Industry-Standard Acronyms are allowed
It’s okay to use acronyms for industry standards.
Acronyms such as Pci, Acpi, Smbios, Isa, (capitalized per the variable naming convention) are all legal to use without defining their meaning.
If you reference an industry standard acronym, the file header must define to which version of the specification the code is written. Thus, a PCI resource manager would state that it was coded to follow the PCI 2.2 Specification and which optional features it included support for.
Capitalize Acronyms in comments and documentation to match their industry standard use.
For example, use “PCI” in comments and documentation, and “Pci” for functions, files, etc.
The table below lists the acronyms that are considered integral to the EDK II vernacular, and may be used without defining their meaning in a comment.
</span></span>Table 2 - 3. EFI Supported Acronyms
Acronyms | In an Identifier | Description |
---|---|---|
ACPI | Acpi | Advanced Configuration and Power Interface |
AGP | Agp | Accelerated Graphics Port |
ANSI | Ansi | American National Standards Institute |
ASCII | Ascii | American Standard Code for Information Interchange |
ATA | Ata | Advanced Technology Attachment |
ATAPI | Atapi | Advanced Technology Attachment Packet Interface |
BFD | Bfd | Boot Flash Device |
BIOS | Bios | Basic Input/Output System |
BIS | Bis | Boot Integrity Services |
CMOS | Cmos | Complementary metal oxide semiconductor |
CPU | Cpu | Central processing unit |
CRC | Crc | Cyclic Redundancy Check |
DMA | Dma | Direct Memory Access |
DXE | Dxe | Driver Execution Environment |
EFI | Efi | Extensible Firmware Interface |
FD | Fd | Flash Device |
FIFO | Fifo | First In First Out |
FV | Fv | Firmware Volume |
GUID | Guid | Globally Unique Identifier |
IEC | Iec | International Electrotechnical Commission |
ISA | Isa | Industry Standard Architecture |
ISO | Iso | International Standards Organization |
NVRAM | Nvram | Nonvolatile Random Access Memory |
PCI | Pci | Peripheral Component Interconnect |
PEI | Pei | Pre-EFI Initialization environment |
RAM | Ram | Random Access Memory |
ROM | Rom | Read-Only Memory |
SRAM | Sram | Static Random Access Memory |
TPL | Tpl | Task Priority Level |
UEFI | Uefi | Unified Extensible Firmware Interface |
UNDI | Undi | Universal Network Driver Interface |
USB | Usb | Universal Serial Bus |
VGA | Vga | Video graphics array |
</span></span></span></span>File Names
There is no limit to file name lengths.
Do not assume that file names must be 8.3 compatible. Be reasonable though. Let the file names be as long as necessary, but no longer. Some operating systems limit file names to 32 characters.
Spaces in file and directory names are NOT permitted.
Allowing spaces would cause problems with certain versions of existing industry tools and does not provide additional clarity.
Never start file names with numbers.
Most source control systems will not be able to handle file names that start with numbers.
Non-standard characters shall not occur in file names.
All file names within an EDK II source tree must comply with the following regular expression:
[A-Za-z][_A-Za-z0-9-]*\.[A-Za-z0-9]+
That is, a letter followed by zero, or more, letters, underscores, dashes, or digits followed by a period followed by one or more letters or digits.
</span></span></span></span>Identifiers
Identifiers shall not rely on the significance of more than 31 characters.
Identifiers (variable names, labels, structure tags, derived macro names, etc.) may be an arbitrary length. The ISO standard only guarantees that language processors only pay attention to the first 31 symbols when comparing identifiers. Note that the same ISO standard requires that external labels (those visible to the linker) be unique in their first six characters. Since it has been confirmed that 31 character / case significance is supported by EDK II supported tool chains, there is no requirement to ensure uniqueness of externals within the first 6 characters.
</span></span>Always make identifier names that are visually distinguishable.
While not as big an issue as it has been in the past, when choosing labels ensure that the label is unlikely to be confused with other labels used in the file. Ensure that long label names vary by more than one or two characters. Ensure that labels don’t vary between zero and oh (0 and O), one and ell (1 and l). Some also consider 2 and Z, and 5 and S to be similar.
</span></span></span></span></span>Hungarian Prefixes
Use of Hungarian notation is not allowed
This set of detailed guidelines for naming variables and routines is a convention widely used with the C programming language, especially in Microsoft* Windows* programming. An example of a non-compliant variable named with the Hungarian conventions follows:
bmRequestType; // Byte mask, First byte in the USB message header
pachInsert; //A pointer to an array of characters to insert.
Global data and module data shall be prefixed with ‘g’ or ‘m’, respectively. Pointer variables may optionally be prefixed with ‘p’. These are the only exceptions to the prohibition against Hungarian notation.
Any variable with file scope, or better, shall be prefixed by an ‘m’ or ‘g’
There are no exceptions to this rule. The ‘m’ prefix identifies a variable with module scope, while a ‘g’ prefix identifies a global variable.
gThisIsAGlobalVariableName
mThisIsAModuleVariableName
Pointer variables may optionally be prefixed with a ‘p’
Time has shown that pass-by-value vs. pass-by-reference errors are significantly reduced with only the introduction of a ‘p’ prefix for pointer variables.
Reasons use of Hungarian prefixes not allowed
The abstraction of abstract data types is ignored. Instead, base types based on programming-language integers or long integers are abstracted. Thus, the names are focused on data types instead of the object-oriented abstraction that they represent. This focus is of little value and forces manual type checking that can be accomplished easily by the compiler with warnings promoted to errors.
Hungarian notation combines data meaning with data representation. If you change a data type you have to rename the variable. There is no mechanism to ensure that the names are accurate.
Studies have shown that Hungarian notation tends to encourage lazy variable names. It’s common to focus on the Hungarian prefix without putting effort into a descriptive name.
</span></span></span></span>Function and Data Names
Identifiers shall contain mixed upper- and lower-case text.
Use of all upper- or all lower-case is very difficult to read because compound words cannot be clearly separated.
The names of newly created global entities (such as structures, macros, and defines) shall not use an EFI_ prefix.
From now on, the use of DXE_ and PEI_ prefixes shall be reserved for DXE and PEI drivers, respectively. If a structure happens to apply equally to PEI and DXE, it should use the prefix DXE_. If a structure is local to a particular module only, no special prefix is required.
Acronyms are not capitalized in Function and Data Names.
When all letters in an acronym are capitalized, it makes the prior and subsequent words visually difficult to distinguish.
ThisIsAnExampleOfWhatToDoForPci
Never use C keywords or the names of symbols declared in the standard header files as internal symbols.
When you need to use the name of an existing library function for a user-defined function, each use of the user-defined function must be paired with a corresponding comment. The ISO standard does not, however, guarantee that the user-defined function will take priority over the library function.
List of the C-reserved keywords.
In principle, the ISO standard, reserves all names beginning with underscore + capital letter, or with underscore + underscore. External symbols names shall not begin with an underscore.
</span>Table 4: Reserved Keywords
auto | break | case | char | const |
continue | default | do | doublea | else |
enum | extern | floata | for | goto |
if | int | long | register | return |
short | signed | sizeof | static | struct |
switch | typedef | union | unsigned | void |
volatile | while | inline | restrict | wchar_t |
bool | true | false | NULL | _Boolb |
_Complexb | _Imaginaryb | andc | and_eqc | bitandc |
bitorc | complc | notc | not_eqc | orc |
or_eqc | xorc | xor_eqc |
Floating point operations are not recommended in UEFI firmware.
These keywords are specific to C99 and are not reserved in C++.
Macros defined in header iso646.h. These identifiers are reserved in C++ and are defined as part of the C Standard Library.
In addition to those listed, the identifiers asm and fortran are common language extensions and should also be treated as reserved.
</span></span></span></span>Type and Macro Names
Use all capital letters for both #define and typedef declarations.
This clearly differentiates static declarations from dynamic data types.
Each word of a concept shall be separated by an underscore character.
The underscore effectively separates the words, making names more readable.
The use of the “_t” suffix, designating a type, is not allowed.
typedef UINT32 THIS_IS_AN_EXAMPLE_OF_WHAT_TO_DO_FOR_PCI;
The names of guard macros shall end with an underscore character.
The guard macro, used in the #ifndef at the start of an include file, uses a postfix underscore character ‘_’, in its name in order to prevent collision with other names that follow the naming convention. This may not be sufficient for header files that don’t have a unique name. In that case, additional text may have to be added to the macro name in order to make it unique. This may not be required if the header files are mutually exclusive.
#ifndef FILE_NAME_H_
#define FILE_NAME_H_
...
#if (A_NUMBER > 72)
...
#else // NOT (A_NUMBER > 72)
...
#endif // (A_NUMBER > 72)
...
#endif /* FILE_NAME_H_ */
The #else and #endif clauses of conditional compilation blocks shall be commented to identify their context.
If a conditional compilation construct spans more than seven lines, a comment shall be added to the construct’s #else and #endif clauses identifying the block the clause is associated with. This is illustrated in the preceding code example. The comment shall be on the same line as the #else or #endif clause.
</span></span></span></span>Global & Module Variables
There is often confusion about what constitutes module variables versus global variables. Technically, both global and module variables are defined at file scope with external linkage. A module variable is intended to only be accessed across a small set of related routines that have strict rules for accessing the data; in effect, constrained to the set of files described within a single .inf file. A global variable is intended to be accessed throughout the firmware, usually indirectly through a protocol pointer or similar mechanism.
This is important when the time comes to maintain a module. A module variable should be fairly safe and easy to change because it is only accessed from a small number of routines. On the other hand, a global variable is accessed throughout the firmware and as the firmware evolves more code will tend to access the data resulting in a large number of uses to track down.
Recommendations for Global and Module Variables
The use of global and module data is strongly discouraged.
Global variables are appropriate for GUID, protocol, PPI definitions and other immutable objects. Attempting to create global variables can cause many problems, including: increased image size and variables actually residing in ROM.
The use of global and module variables may be appropriate for solving certain programming issues. A module is defined to be a set of data and routines that act on that data. Thus, in EFI a protocol could be thought of as a module. A complicated protocol may be built out of several smaller modules.
Use locking to protect access to global and module variables.
This protection is strongly encouraged and especially useful for data that is accessed at various task priority levels.
</span></span></span></span>Name Space Rules
ISO C defines several name spaces (see ISO/IEC 9899:1994 6.1.2.3). The same name could be used in a separate name space for a completely different item.
Name spaces are defined as:
label names
tags of structures, unions and enumerators
Members of structures or unions
All other identifiers.
Name space and scope are not synonymous. Name space rules do not apply to scope. Scope is described in "Scoping Rules" on page 39.
Names shall be used consistently within the same type.
For example, structure tags may only be reused as structure types, and union tags may be reused only for union types.
typedef struct MyStruct {
int one;
int two;
int three;
} MY_STRUCT;
Because of the similarity of MyStruct to MY_STRUCT, they may only be used to refer to the same structure type.
No identifier in one name space may be reused as an identifier in another name space
Exceptions are structure member and union member names.
typedef struct StructOne {
INT32 one;
INT16 two;
struct StructOne *MySelf;
} STRUCT_ONE;
typedef struct StructTwo {
INT16 one;
INT8 *two;
struct StructTwo *MySelf;
} STRUCT_TWO;
typedef struct {
STRUCT_ONE *StructOne; // NOT ALLOWED
STRUCT_TWO *StructTwoPtr; // ALLOWED, it is unique
} BAD_STRUCT;
</span></span></span>A typedef name shall be a unique identifier.
The name that appears at the end of a typedef (STRUCT_ONE and STRUCT_TWO in the example in 4.5.2) is known as a typedef name. Because of ambiguity in the C specifications, and to avoid confusion, and once a typedef name is used in a structure declaration, it may not be declared elsewhere
- Including the declaration in a header file that is then included in a number of files is not a violation of this rule.
</span>A tag name shall be unique.
The name after the ‘struct’ in structure definitions (“StructOne” and “StructTwo” in the example in 4.5.2) is known as a structure tag or simply a tag. To avoid confusion, once a tag is used for declaring a structure it shall not be declared elsewhere.
- Including a header file that contains a structure definition is not a violation of this rule.
</span>Prefix module-scope identifiers for cleaner namespaces.
The use of prefixes is not an absolute requirement, but has been shown as a successful method of avoiding namespace pollution and makes it easier to meet other naming requirements. A useful prefix is the module’s name. For example, the UEFI Shell uses the prefix “Shell” for its identifiers.
SHELL_FREE_NON_NULL (Buffer);
ShellCommandLibConstructor (ImageHandle, SystemTable);
</span>
Source Files
</span></span></span></span></span></span>General Rules
Lines shall be 120 columns, or less
Preferably, limit line lengths to 80 columns or less. When this doesn’t leave sufficient space for a good postfix style comment, extend the line to a total of 120 columns. Having some level of uniformity in the expected width of the source is useful for viewing and printing the code.
Do not use tab characters
Tabs shall be set in all editors to expand to two spaces. All indentation is on two space boundaries. There are no exceptions to this rule! This rule makes code look the same in all editors.
Files may only contain the ASCII characters 0x0A, 0x0D, and 0x20 through 0x7E
Files should be saved using either ASCII or UTF8 encoding.
Only escape sequences defined in the ISO C standard shall be used in string literals.
Implementing hexadecimal escape sequences, ‘\x20’ for example, is prohibited because they vary from compiler to compiler.
The ISO standard defines octal escape sequences: ‘\102’, for example. Because of the similarity to decimal values, and octal having fallen into disuse, use of this construct is prohibited. The only exception to this rule is ‘\0’.
Other than ‘\0’, the only permissible escape sequences are:
</span>Table 2 - 1. Permissible Escape Sequences (ISO/IEC 9899:1990 6.1.3.4)
\a | Alert: Visual or audible alert | \b | Backspace: Move to previous position |
\f | Form Feed: Move to next logical page | \n | New Line: Move to start of next line |
\r | Carriage Return: Move to start of line | \t | Horiz. Tab: Move to next tab position |
\v | Vert. Tab: Move to next Vert. Tab pos. | \’ | Single Quote |
\” | Double Quote | \0 | NUL character |
\\ | Single Backslash |
Octal constants (Base 8) shall not be used.
The C language specification has defined numbers whose first digit is zero as octal, so 010 is decimal 8. The use of octal has declined considerably since C was first defined but this construct remains for backwards compatibility. Its use is prohibited. In particular, do not be tempted to use the zero prefix in tables of numbers to ensure visual alignment:
Address[0] = 00130; // Decimal 88
Address[1] = 01450; // Decimal 808
Address[3] = 81200; // Decimal 81200
…
</span></span></span></span></span></span>Only use CRLF (Carriage Return Line Feed) line endings.
Use Windows, or MSDOS, style line endings. Do NOT use Unix / Linux / MacOS / OS-X file formats.
All files must end with CRLF
The last two characters in any source file within EDK II must be a CRLF: 0x0D followed by 0x0A.
Trigraphs shall not be used
Trigraphs are a construct to allow character representations that do not support all ASCII characters to enter the equivalent of the ASCII character. Trigraphs are three characters long (hence the “tri”). The first two characters are “??” while the third character disambiguates the trigraph. Technically therefore, a [5] could be written a??(5??). Trigraphs have provided both confusing and unnecessary and are prohibited.
</span>In-line assembler shall not be used
There are really no reasons for in-line assembler to be used in EDK II code. The only exceptions in this case are largely associated with the lowest level Architectural Protocols. Using in-line assembly language deviates against the Scope rules defined in "Scope" on page 1because it is an extension to standard C. This.
Do not use #pragma, except for #pragma pack (#).
The only other exception for this would be in the ProcessorBind.h file.
</span>Spacing
Some people claim that spacing is not important and that spacing rules in a coding style are burdensome and bogus. Review the following example to see why spacing is important, especially in C:
int i;main(){for(;i["]<i;++i){--i;}"];read('-'-'-',i+++"hello,
world!\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);}
Dishonorable mention, Obfuscated C Code Contest, 1984.
Author requested anonymity.
</span></span></span></span></span>Vertical Spacing
Use blank lines to
make code more readable
group logically related sections together.
There shall be only one statement on a line
This requirement does not include for loops, where the initial, conditional, and loop statements may go on a single line.
The if and while statements are no exception
The conditional and code always go on a separate line.
It should be:
if (MyVar != 0) {
MyTrueCode ();
}
An open brace ‘{’ goes on the same line as the closing parenthesis ‘)’ of simple predicate expressions
This requirement includes functions and data. A simple predicate expression is one containing zero or one operator which fits on the same line as the keyword.
while (MyVar != 0) {
A close brace ‘}’ always goes at the beginning of the last line of the body
Indent the brace to match the first line of the construct.
while (MyVar != 0) {
MyTrueCode ();
}
A close brace may share a line with the else {, else if () {, and do-while constructs
} else {
} else if (foo) {
} while (bar);
Each sub-expression of a complex predicate expression must be on a separate line
Predicate expressions containing multiple operators with sub-expressions joined by && or || must have each sub-expression on a separate line. The opening brace, ‘{‘ of the body shall be on a line by itself and aligned in the starting column of the associated keyword.
while ( ( Code == MEETS_STANDARD)
&& ( Code == FUNCTIONAL))
{
ShipIt();
}
</span></span></span></span>Horizontal Spacing
Unless explicitly stated otherwise, space may be one or more spaces long
Always put space before and after binary operators.
This space makes both operands much easier to read.
if (MyVar != 0) {
MyTrueCode ();
}
Do not put space between unary operators and their object
If ((--MyInteger) > 0) {
Subsequent lines of multi-line function calls should line up one or two tab-stops from the beginning of the function name
Use either one or two tab stops to ensure that each parameter is indented at least two spaces after the function name. Either of the below examples is acceptable:
Status = gBS->AllocatePool (
EfiBootServicesData,
sizeof (DRIVER_NAME_INSTANCE),
&PrivateData
);
Status = gBS->AllocatePool (
EfiBootServicesData,
sizeof (DRIVER_NAME_INSTANCE),
&PrivateData
);
Always put space after commas or semicolons that separate items
This punctuation is not necessary if no code or comments follow the comma or semicolon.
EfiLibAllocateCopyPool (Size, DevicePath);
for (Size = 0; FileName[Size] != 0; Size++) {...
Always put space before an open parenthesis
The only exception is macro definitions.
if (...
while (...
EfiLibAllocateCopyPool (...
Put a space before an open brace if it is not on its own line
if () {
while () {
Do not put spaces around structure member and pointer operators
Data.Index
Pointer->Index = *Ptr;
Do not put spaces before open brackets of array subscripts
Array[(Max + Min) / 2]
Use extra parentheses rather than depending on in-depth knowledge of the order of precedence of C
(The order of precedence should be the compiler’s job, not yours.)
Consider the following expression:
8 | 8 == 8
On first glance, one might think that the expression would evaluate to TRUE. This is not the case. The bitwise OR operator, ‘|’, has lower precedence than the equality operator, ‘==’. This results in the expression being evaluated as if one had entered:
8 | ( 8 == 8 )
This evaluates to the value 9.
Align a continuation line with the part of the line that it continues.
Value = (GetData (BubbaBaes + BUBBA_HIGH_DATA) << 8) |
GetData (BubbaBaes + BUBBA_LOW_DATA);
</span></span></span></span></span></span>File Heading
Every new file shall begin with a file header comment block
This block shall begin on the first line of the file. This is a Doxygen file descriptor comment block, so line 1 of the file will be:
/** @file
And the comment will end with:
**/
The File Heading comment block is comprised of the following sections: File Description, Copyright, License, and the optional Specification Reference and Glossary sections.
/** @file
File Description.
Copyright
License
Specification Reference
Glossary Section
**/
The following example begins each body line with a tab (two spaces). This is the preferred indentation, but two tabs (four spaces) is also acceptable.
Example:
/** @file
Brief description of the file’s purpose.
Detailed description of the file’s contents and other useful
information for a person viewing the file for the first time.
Copyright (C) –20XX, Acme Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of
the BSD License which accompanies this distribution. The full
text of the license may be found at
http://opensource.org/licenses/bsd-license.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS"
BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED.
@par Revision Reference:
- PI Version 1.0
@par Glossary:
IETF - Internet Engineering Task Force
NASA - National Aeronautics and Space Administration
**/
File Description
The file description consists of a brief, one sentence, description of the file’s purpose as well as a detailed description of the files purpose and content.
The brief description begins on the second line of the comment block and terminates at the first period. Do not include text indicating that the file is a header, include, declaration, or definition file as this is intrinsically obvious.
The detailed description follows the brief description, separated by a blank line. All subsequent text and blank lines are part of the detailed description until terminated by a Doxygen command or the end of the comment.
- The Copyright Notice and License comprise the last paragraph of the detailed file description. They are described separately, below.
The file description describes the purpose of the file (why the file exists), a general description of what it contains, and the relationship of the file to a particular module or modules, if any.
Copyright
The first line of the last paragraph of the file description is made up of the copyright notice. The copyright notice must consist of the following text with the FIRST and LAST symbols replaced with the year the file was created and the year the file was last edited, respectively.
Copyright (C) FIRST - LAST, Acme Corporation. All rights reserved.<BR>
A file that has been created but not edited in subsequent years would have a copyright notice with a single date, such as:
Copyright (C) 2007, Acme Corporation. All rights reserved.<BR>
If this file is subsequently edited, the copyright notice would be updated as follows.
Copyright (C) 2007 - 2014, Acme Corporation. All rights reserved.<BR>
The FIRST - LAST format for the copyright date, as described above, is the only format allowed. Do not use a comma separated list or keep updating a single date. The space surrounding the hyphen, ‘-’, between the FIRST and LAST dates is optional.
The <BR> at the end of the line is required. Doxygen uses XML for its internal format, so repeated spaces and new lines are treated as a single space. The <BR> will force Doxygen to start the following text, the license notice, on a new line.
License
EDK II code files may contain one of several different licenses, depending upon the location and content of the file. The correct license will be determined by the project leader at the time the file is created. In most cases, the license will be the same as for other files in the module or package.
The majority of the files in EDK II contain the following “BSD” license.
This program and the accompanying materials are licensed and made
available under the terms and conditions of the BSD License that
accompanies this distribution. The full text of the license may be
found at http://opensource.org/licenses/bsd-license.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR
IMPLIED.
The license will follow the copyright notice without an intervening blank line. It will be separated from the Specification Reference, if present, by a single blank line.
Specification Reference
If the file declares or implements something described in one or more UEFI or Industry Standard specifications, it must include a specification reference section in the file description comment block. The section begins with a Doxygen directive:
@par Revision Reference:
Each specification is listed on a separate line. All specification references must use the list format. An indented line beginning with a dash character, ‘-’, indicates list format.
@par Revision Reference:
UEFI Version 2.2
PI Version 1.0
</span></span>Glossary
If the file uses a non-standard Abbreviation or Acronym, it must include a Glossary section in the file description comment block. The section begins with a Doxygen directive:
@par Glossary:
Each Glossary definition is listed on a separate line. All Glossary definitions must use the list format.
@par Glossary:
IETF - the Internet Engineering Task Force
NASA - National Aeronautics and Space Administration
</span></span></span></span></span>Include Files
All C include file names shall contain only one extension and it must be .h.
Using only one extension dramatically simplifies build issues and standardizes naming.
Every include file shall have a unique name.
The name of all include files, within the EDK II code base, must be unique. The uniqueness test applies to the entire path used in the #include directive. For example:
#include <Peach/Pit.h>
#include “Olive/Pit.h”
#include <MoneyPit.h>
#include “OpenPit.h”
These are unique, even if the file name itself is not, as long as the preceding path component is included.
To see why this is necessary, consider a package, FruitPkg, that has the following in its DEC file:
[Includes]
Include
Include/Olive
Include/Peach
Both the Include/Olive and Include/Peach directories contain a file Pit.h. It then becomes ambiguous which file is being referenced if one encounters #include <Pit.h> in a source file. This ambiguity would be compounded if another package, also dependent upon FruitPkg, contained a Pit.h file in its Include directory.
Existing automatically generated include files, such as AutoGen.h, are exempted from this rule. It is not mandatory to rename pre-existing include files.
Unique file names may also be formed by appending or prepending a short character sequence, such as the module or package name in which the file resides, or an abbreviation of one of these, to the file name.
PeachPit.h OlivePit.h MoneyPit.h PitBoss.h
Include files shall not consist mainly of include directives.
This type of omnibus header file can significantly increase the time required to rebuild a project. If any of the included files changes, every file that includes the omnibus file will have to be recompiled; even if that particular file did not use the changed header file.
Include files may include only those headers that it directly depends upon.
This maintains proper dependency relationships between the files and allows the header file to be used without prior knowledge of its dependencies.
All include file contents must be protected by a #include guard.
Also known as a “macro guard”, use #include guards to avoid multiple inclusions when dealing with the include directive. Adding #include guards to a header file makes that file idempotent.
#ifndef FILE_NAME_H_
#define FILE_NAME_H_
...
#endif // FILE_NAME_H_
Avoid duplicating the guard macro name in different header files. Including a duplicate guard macro name prevents the symbols in the other from being defined. Names starting with one or two underscores, such as _MACRO_GUARD_FILE_NAME_H_, must not be used. They are reserved for compiler implementation.
With modern programming practices, particularly include files including other include files, it is almost impossible to avoid including the same file more than once. This can only slow down the processing time and may cause difficult to diagnose issues. To avoid this, the use of macro guards is required in all include files to protect against inadvertent multiple inclusion.
The #ifndef shall be on the first line following the file header comment.
This location ensures that all code is contained.
The #endif shall appear as the last line in the file.
The #endif is followed by a comment consisting solely of the guard token. The line shall end with a carriage return (new line) as the last thing in the file, thus ensuring that all code is contained.
Include files shall contain only public or only private data.
Include files must not contain both types of information. Examples of public include files would be protocol definitions or industry standard specifications (EFI, SAL, ACPI, SMBIOS, etc.). Private data would include functions and internal data structure declarations used only within a single module.
Include files shall not generate code or define data variables.
Including code or defining variables can result in issues that are very difficult to debug.
The sample below shows the suggested order of declarations in an include file. Not all types of declarations are present in every file.
/** @file
Public declarations of bizarre protocols for something.
This is a detailed description of the something for which this
file exists. Something rotates upon the blarvitz allowing
implementation of bizarre protocols. If the blarvitz is NULL,
describe what is happening in more detail. If non-null, then
you should probably also explain your rationale.
Copyright (c) 20XX, Acme Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of
the BSD License which accompanies this distribution. The full
text of the license may be found at
http://opensource.org/licenses/bsd-license.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS"
BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED.
@par Specification Reference:
UEFI 2.3, Chapter 9, Device Path Protocol
PI 1.1, Chapter 10, Boot Paths
**/
#ifndef SAMPLE_THING_H_
#define SAMPLE_THING_H_
/* Include directives for dependent header files */
/* Simple defines of such items as status codes and macros */
/* Type definitions */
/* Function prototype declarations */
/* Protocol declarations */
#endif /* SAMPLE_THING_H_ */
</span></span>Code File Structure
All code generating files use the following general structure. Typically these are C files with an extension of “.c”.
/** @file
Definitions of bizarre protocols for something.
This is a detailed description of the something for which this
file exists. Something rotates upon the blarvitz allowing
implementation of bizarre protocols. If the blarvitz is NULL,
describe what is happening in more detail. If non-NULL, then
you should probably also explain your rationale.
Copyright (c) 20XX, Acme Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of
the BSD License which accompanies this distribution. The full
text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS"
BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED.
@par Specification Reference:
UEFI 2.3, Chapter 9, Device Path Protocol
PI 1.1, Chapter 10, Boot Paths
**/
/* Include necessary header files here */
#include <DxeCore.h>
#include <Uefi.h>
#include “SampleThing.h”
/* Define external, global and module variables here */
/* Function Definitions */
/* If this is a protocol definition, the
protocol structure is defined and initialized here.
*/
</span></span></span>Scoping Rules
There are three components of the C language that interact to affect when a particular variable can be used, or not.
Scope: The context in which an identifier is visible constitutes the scope of that identifier..
Visibility: If an identifier can be referenced within a particular scope it is said to be visible.
Storage Class: Allocation of storage space is controlled by the storage class of an identifier.
</span>Scope
Understanding the C scoping rules is critical for good programming. The various identifier scopes encountered are: file, prototype, function, and block or local scope.
File Scope
Top-level identifiers and preprocessor macros are said to have file scope. Their scope extends from their declaration point to the end of the source program file. A preprocessor macro can go out-of-scope earlier if a #undef command that cancels its definition is encountered.
Prototype Scope
The identifiers making up the formal parameters in function prototypes have prototype scope. Identifiers with prototype scope have scopes extending from their declaration point to the end of the prototype.
Function Scope
Statement labels have function scope. Function scope identifiers have scope which encompasses the entire function body in which they appear. This means that statement labels can be referenced before they are declared.
Block (local) Scope
Formal parameters in function definitions and data defined within compound statements have block scope. Any group of statements that are encompassed within a pair of braces, { }, is a compound statement. The body of a function is also a compound statement. Compound statements can be nested, with each creating a new scope.
Data declarations may follow the opening brace of a compound statement, regardless of nesting depth, and before any code generating statements have been entered. Other than at the outermost block of a function body, this type of declaration is strongly discouraged.
- Visual C++ gives all structure declarations File Scope, even though ISO/IEC 9899 specifies that structure declarations may have Block Scope.
Visibility
A declaration of an identifier is visible in some context if a use of the identifier in that context is associated with that declaration. A declaration might be visible throughout its scope, but it might also be hidden by other declarations whose scope and visibility overlap that of the first declaration.
No two different identifiers in a function may have the same name nor may any of the names in a function be the same as those declared at a global or module level.
Identifiers with file scope have the outermost scope. Those with block scope have the innermost scope. Nesting successive blocks creates more inner scopes.
Only disallow instances where an outer definition is hidden by a second inner definition. This rule is not violated when the first definition is not hidden by the second definition.
The following example shows how the scope visibility of identifiers can overlap and hide each other. Never write code that does this.
1 UINTN MyVar = 7; // File scope
2
3 VOID
4 MyFunction (
5 OUT UINT32 *MyVar // Function scope
6 )
7 {
8 UINT32 i;
9
10 for ( i = 0; i < 5; ++i) {
11 UCHAR8 MyVar = i; // Block scope
12 INT16 i = 12;
13
14 MyVar += 'A';
15 process ( MyVar, i);
16 }
17 *MyVar = i;
18 }
19
20 main()
21 {
22 UINT32 George = 4;
23
24 MyFunction ( &George);
25 process ( MyVar, 0);
26 }
27
In the above example, there are three declarations of MyVar:
On line 1, MyVar is defined with file scope and value 7. This scope extends from line 1 through line 26.
On line 5, MyVar is declared as a formal parameter of MyFunction. Its context extends from line 5 through the end of the function on line 18.
On line 11, MyVar is declared with block scope. From its declaration point on line 11 through the end of the block in which it was declared, this declaration of MyVar will be in scope. It is initialized to the current value of i.
To test yourself on your understanding of scope and visibility rules, determine the value and associated declaration for each use of MyVar before reading further.
The first use of MyVar is on line 14. Its associated declaration is on line 11. Each time through the for loop it will have the values ‘A’, ‘B’, ‘C’, and ‘D’ in succession.
On line 15, MyVar is used again with its associated declaration on line 11 with the same succession of values assigned as on line 14.
MyVar, on line 17, associates with the formal parameter declaration on line 5. In this case the value of i, which is 5, is stored in the location MyVar points to. The location is established in the call to MyFunction on line 24.
The last use of MyVar occurs on line 25. This occurrence associates with the declaration on line 1 and has the value 7.
Things get extremely tricky on line 12. The identifier i, which is the control variable for the enclosing for loop, is declared with a different type and value. It is ambiguous as to which i was wanted in line 11. How does this affect the for loop? What will be the value of i at lines 15 and 17?
The scope rules tell us the answers, but they still aren’t obvious.
The i on line 10 is outside the block, which is the body of the for loop. It associates with the declaration on line 8, so the for loop will continue to work as expected.
On line 11, MyVar will be initialized to the current value of i. It is compiler dependent whether this is the first value of i, 0, or the value of i for each loop.
Line 12 declares a new variable i which is given the value 12. C scoping rules state that a scope begins at the declaration point, not at the beginning of the block in which the declaration appears. Because of this, the i used on line 11 is not the same i declared here.
The value of i used on line 15 is 12, the value of the associated and currently visible identifier with that name.
As you can see, using the same identifier at different scopes can be confusing at best. All it takes is one mistake and a bug is introduced that is very hard to locate.
</span>Compile-Time Names
So far we have been talking about variable and function identifiers, which have an existence at run time. However, the scope and visibility rules apply equally to identifiers applied to objects that don’t necessarily exist at run time: typedef names, type tags, enumeration constants, macros, and labels.
Macros and labels follow the rules outlined for them in "Scope" on page 39. The other compile-time names follow the same scope and visibility rules as any variable defined at the same location.
</span>Storage Class
extern
A special case of scope and visibility is the external identifier, also called an identifier with external linkage. All instances of an external identifier, among all the files making up a C module, are forced to refer to the same object or function. Each instance of the external identifier must be declared with the same type in each file or else the result is undefined.
External names are declared using the extern keyword. In C89, and earlier dialects, external identifiers declared at file scope are implicitly extern. But, not all identifiers declared extern were external.
The compilers supported by EDK II follow the C99 specification for extern. All declarations of the external variable must use the extern keyword. There must be a single definition of the external variable which does not use the extern keyword. This definition may also include an initializer.
By convention, external names are declared at the top level of a C program and therefore have file scope. For EDK II, external names must be declared in a single header file and must be defined at the top level of a C file as specified in "Compile-Time Names" on page 42. Thus, while it might be legal C, do not declare external variables anywhere other than at the top level of a file as specified by this document.
Static
An object declared STATIC has either file or block scope.
Do not reuse an object or function identifier with static storage duration.
Throughout the set of source files defined within a single .inf file, do not reuse an identifier with static storage duration. The compiler may not be confused by this, but the user may confuse unrelated variables with the same name.
Functions should not be declared STATIC.
Some source-level debuggers are unable to resolve static functions. Until it can be verified that no one is dependent upon a debugger with this limitation, it is strongly recommended that functions not be declared static.
</span></span>Preprocessor Directives
</span></span></span></span>#include
Use the proper file delimiters when including files
Use either double quotes or angle brackets. A file name delimited by angle brackets, <FileName.h>, indicates that the compiler should search the default include paths and those specified by ‘-I’ directives on the compiler command line (System Include Files). If one uses double quotes to delimit the file name, “FileName.h”, the compiler will first search the directory containing the file being compiled before then searching the System include paths.
The general rule to be derived from this is that one should use double quotes to include files in the same directory as, or a subdirectory of, the file being compiled, and angle brackets for all other include files.
#include <Uefi.h> /* System include file. */
#include “SampleThing.h” /* In same directory as the C file. */
Include file paths shall be relative and shall not contain “..” elements.
All include paths must be relative to either the current .c file, or a predefined include directory.
</span></span></span></span></span></span>Macros
Functional macros are generally discouraged.
Parameterized macros are difficult to debug, have difficult syntax, do not encourage strong commenting, and generally negatively impact maintainability and understandability of code. Macros are appropriate for some concepts, such as containment records and include path abstraction.
Macros follow the standard data naming conventions used by typedef and #define.
The main reason for making a macro different from a function is the difference in the order of precedence that can occur between poorly constructed macros and functions.
Overusing parentheses is strongly encouraged.
An order-of-precedence bug in a macro is very hard to debug. The following are examples of macro construction:
#define BAD_MACRO(a, b) a*b
#define GOOD_MACRO(a, b) ((a)*(b))
The following examples should explain the difference between BAD_MACRO () and GOOD_MACRO ():
BAD_MACRO (10, 2) and GOOD_MACRO (10, 2) both evaluate to 20.
BAD_MACRO (7+3, 2) returns 13 = 7 + (3*2).
GOOD_MACRO (7+3, 2) returns 20.
Also, consider the following expression:
8 | 8 == 8
On first glance, one might think that the expression would evaluate to TRUE. This is not the case. The bitwise OR operator, ‘|’, has lower precedence than the equality operator, ‘==’. This results in the expression being evaluated as if one had entered:
8 | ( 8 == 8 )
This evaluates to the value 9. The desired result of TRUE, (1), can be achieved by specifying the expression as:
((8 | 8) == 8)
Macros must have comment blocks like functions.
Macros can be very difficult to debug, so explicit descriptions of the input, output, and behavior are required. This is true whether it is a parameterized or a simple substitution macro.
Parameterized macro definitions shall not have a space between the name and the ‘(.’
Failure to do this will cause the build to break.
#define GOOD_MACRO(a, b) ((a)*(b))
This is because the compiler has no way to differentiate between
#define SIMPLE_MACRO (a) (TXT)
which substitutes all subsequent occurrences of SIMPLE_MACRO with (a) (TXT), and
#define PARAM_MACRO(a) (a) (TXT)
which defines a parameterized macro.
When using a macro, there must be a space between the name and the ‘(’ to comply with function calling conventions.
Failure to separate macro names from parameters negatively impacts readability and consistency with other coding style rules.
GOOD_MACRO (7+3, 2)
Single-line Functions
Most uses of parameterized macros can be replaced by one or two line functions. The compilers will almost always in-line the function resulting in the same effect as the parameterized macro. An additional benefit of single-line functions is the type checking the compiler can now provide.
</span></span>Declarations and Types
</span></span> </span>Common Data Types
The UEFI Specification defines a set of common data types that must be used to ensure portability between different compilers and processor architectures.
Any abstract type that is defined must be constructed from other abstract types or from common EFI data types.
The use of int, unsigned, char, void, static, long is a violation of the coding convention.
The corresponding EFI types must be used instead.
"EFI Data Types" below contains the common data types that are referenced in the interface definitions defined by this specification. Per the UEFI Specification, version 2.3.1:
“Unless otherwise specified, all data types are naturally aligned. Structures are aligned on boundaries equal to the largest internal datum of the structure, and internal data is implicitly padded to achieve natural alignment.”
</span>Table 2 - 2. EFI Data Types (slightly modified from UEFI 2.3.1)
Mnemonic | Description |
BOOLEAN | Logical Boolean. 1-byte value containing a 0 for False or a 1 for True. Other values are undefined. |
INTN | Signed value of native width. (4 bytes on IA-32, 8 bytes on X64, and 8 bytes on the Intel® Itanium® processor family) |
UINTN | Unsigned value of native width. (4 bytes on IA-32, 8 bytes on X64, and 8 bytes on the Intel® Itanium® processor family) |
INT8 | 1-byte signed value. |
UINT8 | 1-byte unsigned value. |
INT16 | 2-byte signed value. |
UINT16 | 2-byte unsigned value. |
INT32 | 4-byte signed value. |
UINT32 | 4-byte unsigned value. |
INT64 | 8-byte signed value. |
UINT64 | 8-byte unsigned value. |
CHAR8 | 1-byte character. |
CHAR16 | 2-byte character. Unless otherwise specified, all strings are stored in the UTF-16, 2-byte, encoding format as defined by the Unicode 2.1 and ISO/IEC 10646 standards. |
VOID | Undeclared type. |
EFI_GUID | 128-bit buffer containing a unique identifier value. Unless otherwise specified, aligned on a 64-bit boundary. |
EFI_STATUS | Status code. Type UINTN. |
EFI_HANDLE | Handle to a device driver. Type VOID *. |
EFI_EVENT | Handle to an event structure. Type VOID *. |
EFI_LBA | Logical block address. Type UINT64. |
EFI_TPL | Task priority level. Type UINTN. |
"Modifiers for Common EFI Data Types" on page 47 defines modifiers that are used in function and data declarations. The IN, OUT, OPTIONAL, and UNALIGNED modifiers are used only to qualify arguments to a function. They should never appear in a data type declaration. The EFIAPI modifier is used to ensure the correct calling convention is used between different modules that are not linked together. Use this modifier at the entry of drivers, events, and member functions of protocols.
The EFIAPI modifier must be used for all UEFI defined API functions, as well as for any function that takes a variable number of arguments. All protocol functions as well as public functions exposed by drivers must also be declared EFIAPI. This establishes a common calling convention for functions that could be referenced by other code that has potentially been built using a different compiler, with a different native calling convention.
</span>Table 2 - 3. Modifiers for Common EFI Data Types (reference the UEFI Specification and Beyond Bios)
Mnemonic | Description |
IN | Datum is passed to the function. |
OUT | Datum is returned from the function. |
OPTIONAL | Datum that is passed to the function is optional, and a NULL may be passed if the value is not supplied. |
UNALIGNED | Datum is byte packed and is not naturally aligned. |
VOLATILE | Declares a variable to be volatile and thus exempt from optimization to remove redundant or unneeded accesses. Any variable that represents a hardware device should be declared as VOLATILE. |
CONST | Declares a variable to be of type const. This type is a hint to the compiler to enable optimization and stronger type checking at compile time. |
EFIAPI | Defines the calling convention for EFI interfaces. All EFI intrinsic services and any member function of a protocol must use this modifier on the function definition. |
</span>Constants
EFI Constants
"EFI Constants" below lists the EFI constants that should be used to represent certain concepts.
</span>Table 2 - 4. EFI Constants
Mnemonic | Description |
TRUE | One = ( 1 < 2 ) == 1; Any non-zero value is TRUE. |
FALSE | Zero = ( 2 < 1 ) == 0 |
NULL | VOID pointer to zero. ((void*)0) |
</span></span>Enumerated Types
The elements of the enumerated type must follow the data and function naming convention.
The enum shall be declared as a typedef with the name of the typedef following the type and macro naming conventions in "Type and Macro Names" on page 25.
The last element of the enum should be a maximum member element.
This convention allows for bounds checking on an enum to support debugging and sanity checking the value that is assigned to an enum. It is also recommended that the enum members be named carefully, such that their names would not tend to collide with other variable or function names.
typedef enum {
EnumMemberOne, ///< Automatically initialized to zero.
EnumMemberTwo, ///< This has the value 1.
EnumMemberMax ///< The value 2 here indicates there are two elements.
} ENUMERATED_TYPE;
This obviously will not work if values are explicitly assigned out-of-sequence or are duplicated.
All constants that will be used “as is” should be declared as enums.
An enum does not cause code to be generated until the enum is used, whereas a const int will cause space for the int to be allocated as well as the code generated whenever the int is used. The use of enums allows type checking to be performed, while the use of macros does not.
Macro Constants
Constants that will be used to construct other values should be declared as macros.
These include bit field definitions and masks.
Pointers and Constants
There are three different ways pointers and constants can interact:
Pointer to Constant: CONST UINTN * PointerToConst;
PointerToConst is a variable pointer to a constant UINTN.
Constant pointer to variable: UINTN * CONST ConstPointer;
ConstPointer is a constant pointer to a variable UINTN.
Constant pointer to constant: CONST UINTN * CONST ConstPointerToConst;
ConstPointerToConst is a constant pointer to a constant UINTN.
</span></span></span>Structure Declaration
Structures shall be declared as a typedef with one of two different styles depending on the use of the structure. If the structure is not self-referential, or there is no forward reference to it, the structure may be defined anonymously; see Section "Structure Reference" on page 59.
This anonymous definition is valid because we typedef the structure in the definition.
The structure name and typedef name shall follow the type and macro naming conventions in "Type and Macro Names" on page 25.
Structure instances: Variables, parameters, members, etc., must follow the file, function, and data naming conventions in "Identifiers" on page 22 through "Name Space Rules" on page 26.
Structures are always defined in a typedef struct name {…} type; format.
The “name” tag is allowed only if the structure is self-referential or the target of a forward reference.
Structures shall not be directly declared.
The following are not allowed:
struct name {…}; // OK if object of forward reference
struct {…} variable; // Never OK
struct name {…} variable; // Never OK
Structure Declaration with Forward Reference or Self-Reference
/// Sample forward declaration of a structure.
typedef struct EFI_STRUCT_NAME EFI_STRUCT_NAME;
/// Sample self-referential structure declaration.
typedef struct EFI_STRUCTURE_NAME {
…
struct EFI_STRUCTURE_NAME *StructPointer; ///< Sample self reference
} EFI_STRUCT_NAME;
Structure Declaration without Forward Reference
/** Brief description of sample structure declaration.
*
* Detailed description of purpose and use of this
structure.
**/
typedef struct {
Atype memberOne; ///< Briefly describe memberOne
...
Ztype memberN; ///< Briefly describe memberN
} EFI_STRUCTURE_NAME;
Bit Fields
A member of a structure or union may be declared to consist of a specified number of bits (including a sign bit, if any). That member is referred to as a bit-field. Bit fields differ from other members in that:
Bit fields may only be of type INT32, signed INT32, UINT32, or a typedef name defined as one of the three INT32 variants.
It is compiler defined whether INT32 is signed or unsigned.
The order of allocation of bit-fields within a storage unit is compiler defined.
The alignment of the addressable storage unit is unspecified.
A bit-field may not extend from one storage unit into another.
A bit-field with only a colon and a width (no declarator), indicates an unnamed bit-field. Unnamed bit-fields are useful for padding to conform to externally imposed layouts.
Specifying a bit-field with a width of 0 (zero) indicates that no further bit-fields are to be packed into the unit in which the previous bit-field, if any, was placed.
Visual C++ Specific
The alignment requirement for each non-bit-field member is the same as the largest alignment requirement of the members. Thus, every member will have the same alignment.
A “plain” int bit-field is treated as a signed int bit field.
Bit fields are allocated within a storage unit from least-significant to most-significant bit.
GCC Specific
The alignment requirement for non-bit-field members of structures is determined by the target ABI.
By default, a “plain” int bit-field is treated as a signed int, but this may be changed by the ‘-funsigned-bitfields’ option.
The order of allocation of bit-fields within a unit is determined by the target ABI.
</span></span>C Programming
</span></span></span></span></span>Function Definition Layout
Every function should be constructed to the conventions described in this section.
Precede the function with a Doxygen style comment block.
The function header comment block must describe the intent and purpose of the function, parameters used, and return values.
The line immediately following the function header comment block optionally specifies the storage class of the function.
If the storage class is not specified, the return type will be on the first line following the comment block.
The next line of the function definition must specify the function’s return type.
If the function does not return a value, this line must contain VOID.
The next line contains any optional functional modifiers.
For example, EFIAPI, or other valid modifiers.
The next line contains the function name, left justified, followed by the beginning of the parameter list, “(.”
No parameters are allowed on this line. If no parameters are present, it is acceptable to place the closing parenthesis on the same line, “(VOID).”
A function that takes no parameters shall be declared with VOID as the parameter list.
Declaring a function with an empty parameter list, (), is prohibited.
The next lines contain parameters.
Each line will contain a single argument and will start indented two spaces (one tab stop). Type and argument columns should be aligned to maximize readability and should include appropriate spacing to ensure this alignment. No comments are allowed in this region. Parameters are documented clearly in the function header comment block.
The closing parenthesis is on its own line and is also indented two spaces.
A valid exception exists if the function has no parameters.
Function prototypes have the same form as function definitions, with the exception of requiring a semicolon after the closing parenthesis of the parameter list.
The opening brace of the function body is alone on the next line.
Both the opening and closing brace of the function body must be aligned in the left most column. All other lines of the function body are indented in multiples of two spaces.
/** Brief and Detailed Descriptions.
@param[in] Arg1 Description of Arg1.
@param[in] Arg2 Description of Arg2, which is optional.
@param[out] Arg3 Description of Arg3.
@param[in,out] Arg4 Description of Arg4.
@retval EFI_SUCCESS Description of what EFI_SUCCESS means.
@retval !EFI_SUCCESS Failure.
--*/
EFI_STATUS
EFIAPI
FooName (
IN UINTN Arg1,
IN UINTN Arg2, OPTIONAL
OUT UINTN *Arg3,
IN OUT UINTN *Arg4
);
{
UINTN Local;
...
}
Each argument variable’s type specification should be preceded by IN and/or OUT modifiers.
The modifiers are used to indicate whether the argument is an input or output variable. It is strongly suggested that the IN variables are first and OUT variables come next. If data is both passed in and passed out through a variable, then it should be marked as both IN and OUT. A buffer that is passed into a routine that modifies the contents of the buffer is marked as IN and OUT. "Parameter Modifiers" below describes the usage of the IN and OUT modifiers.
The IN and OUT modifiers may be omitted if the mandatory @param[in,out] descriptions are provided in the function header comment.
</span>Table 2 - 5. Parameter Modifiers
Mnemonic | Description |
IN | Passed by value. For C, this modifier is any argument whose name is not preceded by an asterisk (*). |
IN | Passed by reference, and referenced data is not modified by the routine. An asterisk precedes the argument name. |
OUT | Passed by reference, and the referenced data is modified by the routine. The passed-in state of the referenced data is not used by the routine. |
IN OUT | Passed by reference, and the passed-in referenced data is consumed and then modified by the routine. |
OPTIONAL | Indicates that if a pointer argument is NULL, it is not present. If the value is not NULL, then it is a valid argument and may be used. |
The body of a function is contained within open and close braces that must be in the first column.
File-Scope data definitions must be the first code in a module.
The type definition must start indented and be followed by the variable name with at least one indent between the two. Each variable name must have its own line; do not use a comma to separate multiple declarations. Do not comment data declarations; they should contain self-describing names. If comments are required for complex data declarations, place the comments in the include file that defines the complex data type, or make comments in the routine description block. This restriction does not apply to the members of structures, unions, or enums.
File-Scope Data definitions appearing anywhere but at the beginning of the module are illegal.
</span></span>Function Headings
Every new function created as part of EDK II must have a function header comment block immediately preceding the function definition.
The function header comment block takes the form shown in the example below.
/** Brief description of the function’s purpose.
Detailed description of the function’s purpose and how it
works. Describe algorithms, side-effects, or other attributes
of the function that would be of use to a programmer unfamiliar
with the code.
@param[in] Arg1 Description of Arg1. This can span multiple
lines if needed.
@param[in] Arg2 Description of Arg2.
@retval EFI_SUCCESS Procedure returned successfully.
@retval VALUE Line for each possible return value.
**/
EFI_STATUS
Foo (
IN UINTN Arg1,
IN UINTN Arg2
)
{
// Function body
}
Function comment headings must be present in both the .c file containing the function implementation and in the .h file containing the function prototype.
The function comment heading in the .c file shall, at a minimum, be a duplicate of the heading in the include file. In all cases, the function comment heading in the include file is the authoritative source. Function comment headings in .c files may contain implementation specific comments which are not permitted in the .h file.
Any function that is shared must have the function prototype in a shared .h file.
Private functions may be declared in the .c file implementing them if they are not used in any other file. All such private function declarations must be present at the beginning of the .c file, before any function implementations and after global data.
All public types, macros, and declarations for a module shall be in a single include file resident in the hierarchy of the top-level include directory of the package the module is part of.
</span></span></span></span>Predicate Expressions
Boolean values, variable type BOOLEAN, do not require explicit comparisons to TRUE or FALSE.
Non-Boolean comparisons must use a compare operator (==, !=, >, < >=, <=).
A comparison of any pointer to zero must be done via the NULL type.
"Predicate Expression Examples" below shows examples using the following:
BOOLEAN Done;
UINTN Index;
VOID *Ptr;
</span></span>Table 2 - 6. Predicate Expression Examples
Incorrect | Correct |
If (Index) { | if (Index != 0) { |
If (!Index) { | if (Index == 0) { |
If (Done == TRUE) { | if (Done) { |
If (Done == FALSE) { | if (!Done) { |
If (Ptr) { | if (Ptr != NULL) { |
If (Ptr ==0) { | if (Ptr == NULL) { |
Comparison of unsigned integer types to be >=0 is permitted.
There has been some controversy on this since unsigned integers are always >=0, and some compilers will emit a warning when this type of construct is seen. This is perfectly valid code and, with some compilers, is needed for limit checking against enumerated types. These compilers will assign the type to the enum based upon the range of values the enum is assigned at compile time.
if ((foo >= 0) && (foo < MaxVal)) { ...
If one wants to be perfectly safe in their comparison, the potentially unsigned term can be cast to a signed integer type of sufficient size; if the range of possible values is known.
if ((INTN)foo >= 0) { ...
The ordering of terms in predicate expressions may impact performance significantly.
This is because only enough of the expression has to be evaluated to determine the outcome. For example, the first term in an OR expression that evaluates to TRUE is sufficient to determine that the entire OR expression will be TRUE.
The following code sample consists of a predicate expression within a for loop. The predicate expression is a compound AND expression with four terms. Each term is itself a simple predicate expression.
This is a real example from a previous version of the EDK II code and was used in the implementation of the PERF_END functionality. It finds the first open (EndTimeStamp is zero) performance trace record matching the Handle, Token, and Module parameters of a PERF_END invocation.
for (Index = 0; Index < NumberOfEntries; Index++) {
if (( LogEntryArray[Index].Handle == (EFI_PHYSICAL_ADDRESS) (UINTN) Handle)
&& AsciiStrnCmp (LogEntryArray[Index].Token, Token, PEI_PERFORMANCE_STRING_LENGTH) == 0
&& AsciiStrnCmp (LogEntryArray[Index].Module, Module, PEI_PERFORMANCE_STRING_LENGTH) == 0
&& LogEntryArray[Index].EndTimeStamp == 0
)
{
break; // Exit the enclosing for loop.
}
}
While there is nothing really wrong with this code, a little knowledge of the data it will be working on will allow us to significantly speed things up. Again taking from a real-world example:
NumberOfEntries = 25,172
Target entry is at Index 25,159
There are 532 completed measurement records with the same Handle, Token, and Module values prior to the target.
There are 6 measurement records with the same Handle and different Token and Module values prior to the target.
There are 25,157 completed entries prior to the target.
From this information, we can see that the terms, in order of importance, are:
- EndTimeStamp 1 match (2 max over life of a session)
- Handle 538 matches
- Module 532 matches
- Token 532 matches
We also can determine that this ordering is valid for any measurement. Re-ordering the predicate expression using this information produces:
for (Index = 0; Index < NumberOfEntries; Index++) {
if ( LogEntryArray[Index].EndTimeStamp == 0
&& LogEntryArray[Index].Handle == (EFI_PHYSICAL_ADDRESS) (UINTN) Handle
&& AsciiStrnCmp (LogEntryArray[Index].Module, Module, PEI_PERFORMANCE_STRING_LENGTH) == 0
&& AsciiStrnCmp (LogEntryArray[Index].Token, Token, PEI_PERFORMANCE_STRING_LENGTH) == 0
)
{
break; // Exit the enclosing for loop.
}
}
The new ordering results in 538 fewer 64-bit integer comparisons and 1,069 fewer string comparisons for this single PERF_END invocation. Considering that there will be 25,170 PERF_END invocations one can see how the savings add up to a sizable amount: around 2.7 seconds if the string comparisons only took 100ns each.
</span></span></span></span>Flow Control Statements
The body of looping statements must be compound statements.
The if, for, do, and while statements shall use a compound statement as their bodies, even if it is necessary to use a null compound.
Null compound statements shall occupy three source lines.
The opening brace shall be on the same line as the controlling keyword, followed by a line consisting of a properly indented semicolon, then closed with a closing brace, aligned in the same column as the opening keyword, as the first non-white-space character on the third line.
Any loop that contains no code in the body must use a null compound statement as the body.
For example, the following statement has a null compound for its body.
for (Index = 0; Index < MAX_INDEX; Foo[Index] = Index++) {
;
}
Avoid this type of construct because it is harder to read than other control structures.
if Statements
The if statement shall be followed by a space and then the open parenthesis.
The open parenthesis is followed by a conditional (predicate) expression and a close parenthesis.
There is a space after the close parenthesis followed by an open brace.
The code body follows and is indented by two spaces.
The close bracket is on its own line and indented to the same level as the if.
The following is the allowed if construct:
if (TRUE) {
IamTheCode ();
}
When an else is used, it may start on the same line as the close brace of the if, or be on the following line and aligned with the closing brace.
A single space must separate else from the close and open braces.
An open brace always follows the else.
The following are the allowed if and else constructs:
if (EXPR_1) { IamTheCode ();
} else if (EXPR_2) {
IamTheCode ();
}
else { // Alternative format
IamTheCode ();
}
while and do-while Statements
while statements execute their body zero or more times depending upon the result of a predicate expression. The expression is evaluated at the beginning of the loop and the body is executed if the expression evaluates to TRUE. Code must be constructed so that nothing outside of the while loop is dependent upon the body of the loop having been executed.
while (TRUE) {
IamTheCode ();
}
For those cases where the body of the loop must be executed at least once, there is the do-while statement. In this statement, the predicate is evaluated at the end of the loop, with the statement’s body being re-executed as long as the predicate evaluates to TRUE.
do {
IamTheCode ();
} while (TRUE);
for Statements
A for loop occupies a minimum of three lines. It is comprised of the for keyword followed by three expressions within parentheses, followed by a compound statement. The three expressions within parentheses are separated by semicolons, ‘;’, and consist of the initialization, conditional, and increment expressions. Any one or combination of these expressions may be omitted if needed.
for (Index = 0; Index < MAX_INDEX; Index++) {
IamTheCode (Index);
}
switch Statements
The following is a switch statement:
switch (Variable) {
case 1:
IamTheCode ();
break;
case 2:
IamTheCode ();
break;
default:
IamTheCode ();
break;
};
The case statements are indented either zero tab stops or one tab stop and the bodies of each case one tab stop from the case.
The closing brace of the switch statement should be in the same column as the ‘s’ in the switch keyword.
Always include the “default” case. It should always end with a break statement, even if the break is the last thing before the closing brace.
The indenting of the case statements should be consistent with all other files in the module containing the new .c file. Use the legacy, zero indent, style if any other file within the module uses that style, otherwise you may indent a single tab stop.
A descriptive comment is required in cases where the intention is for a preceding case to fall through to the next case. That is to say, a descriptive comment is required where there is no break preceding the second or beyond case in a switch block.
Goto Statements should not be used (in general)
In almost all cases, it is possible to write the code so that a goto is not needed. If a goto is used, be ready to defend it during review.
It is common to use goto for error handling and thus, exiting a routine in an error case is the only legal use of a goto. A goto allows the error exit code to be contained in one place in the routine. This one place reduces software life cycle maintenance issues, as there can be one copy of error cleanup code per routine.
The goto follows the normal rules for C code. The label must be indented one level less than the code it is marking.
Status = IAmTheCode ();
if (EFI_ERROR (Status)) { goto ErrorExit;
}
IDoTheWork ();
ErrorExit:
return Status;
The above example could have been rewritten as below, eliminating the need for a goto.
Status = IAmTheCode ();
if (! EFI_ERROR (Status)) {
IDoTheWork ();
}
return Status;
</span></span>Structure Definitions
</span>Structure Reference
/** Sample reference to a structure.
*
* Sample code showing a reference to a structure as a
* function parameter. This function should be called as:
* FooName (&Structure);
*
* @param[in] Arg1 A pointer to the sample structure.
**/
VOID
EFIAPI
FooName (
IN EFI_STRUCTURE_NAME *Arg1
);
In any situation, definition of structure instances shall be in the following form:
EFI_STRUCTURE_NAME StructureName;
Never pass structures as function parameters by value. Use the “address of” operator, ‘&’, and pass structures by reference.
FooName (&StructureName);
</span></span>Error Handling and ASSERT
ASSERT macros are development and debugging aids and shall never be used for error handling.
Assertions are used to catch conditions caused by programming errors that are resolved prior to product release.
The EDK II PCD, PcdDebugPropertyMask, can be used to enable or disable the generation of code associated with ASSERT usage. Thus, all code must be able to operate, and recover in a reasonable manner with ASSERTs disabled.
Parameters and conditions that are beyond the programmers control need to be checked programmatically. Care must be taken, though, to ensure that the need for programmatic error handling is minimized.
The ASSERT_EFI_ERROR, ASSERT_PROTOCOL_ALREADY_INSTALLED, and all other ASSERT macros defined in DebugLib.h are covered by this rule.
</span></span>
Documenting Software
</span></span>Documentation Concepts
A program is meant to be read by the programmer, by another programmer at a future date, and by a machine. In this sense it is a kind of publication.
However, the machine is concerned with whether the program compiles, while people are necessarily concerned about coding conventions or style.
Sensible and consistently applied typographic (stylistic) conventions are important to the creation of a clear presentation. Conventions are created to facilitate clarity, should not become an end in and of themselves. As Rob Pike points out, we should avoid typographic silliness and decoration:” . . . keep comments brief and banner free. Say what you want to say in the program, neatly and consistently. Then move on.”
</span>Requirements
The EDK II code documentation shall fulfill the following main functions:
Instruction
It shall serve as:
Working instructions (e.g. error and interrupt handling, data archiving, …)
A working basis to avoid duplication of work
A working basis for software maintenance (e.g. updates, upgrades, troubleshooting)
A basis for brief instruction and training of new staff members; simple training courses
Verification, Validation, and Objective Evidence
Establishes traceability between the code and product requirements
Reference for internal and external auditors (product liability, ISO 9001 certification)
Facilitates project management and monitoring
Increases testability of the software
Communications
Establishes an uniform communication basis for:
All software developers
Contractors and customers
Increases software re-usability
Increases transparency of the software
</span>Interfaces or Protocols
The EDK II architecture forces explicit documentation as it encourages the use of multiple, independent modules. The mechanism for these modules to communicate is a protocol. A protocol is an instance of an API (a class in C++ vernacular) that is named by a GUID. The GUID defines the data representation and member functions of a protocol. Any change to the behavior of a protocol requires the GUID to change. Given this property, each protocol used in EDK II must have an interface document.
</span></span></span></span>Comments
Commenting has always been a delicate matter, requiring taste and judgment. One should assume that others reading the code know the implementation language. Code that is clear, using good type and variable names, should be self-explanatory — at a micro level. Comments should explain the less-than-obvious aspects of the code, at a macro level.
- The comments need to explain why things were done and the big picture of how something works and the ways in which the various pieces relate to each other.
By definition, misleading comments can cause confusion. When you modify code, you should always check the comments to ensure that they accurately document the modified code. Comments are not checked by the compiler, and are therefore not guaranteed to be correct. Comments are even more of a risk following code modification.
Write your comments assuming that they are going to be read by someone with minimal familiarity with the code. Clarity is important, but one should also strive for terse and concise comments. One should be able to see both the comment, and the code being commented on, on the same screen.
Only use C style, “/*”, comments for multi-line comments and on the same line as pre-processor directives.
Compile can vary in their r support for use of // in preprocessor directives (e.g. #define). Note that the mixing of /* ... */ and // is not handled consistently. This goes beyond style issues; various (pre C99) compilers may not behave the same.
Avoid banners or other decoration around blocks of comments.
Banners can be useful to highlight logical divisions within a file; such as before vital sections. This type of usage should be minimized.
Avoid comments where the opening comment characters are alone on a line.
/*
* VIOLATION: Horror Vacui
*/
or
//
// VIOLATION: Horror Vacui
//
Do not include jokes or obtuse references in comments.
“Out of cheese error! Redo from start.”
</span></span></span></span>What NOT to Comment
Do not repeat the code or explain it in a comment.
Comments should clarify the intent of the code or explain higher-level concepts. The code itself should be clear and self-documenting.
There is a famously bad comment:
i = i + 1; // Add one to i
This comment provides no information beyond what is already obvious from reading the code. There are even worse ways to do it, such as:
/**********************************
* *
* Add one to i *
* *
**********************************/
i=i+1;
Do not leave markers in the code.
Don’t leave flags, such as your name, in the code. They may have meaning to you but they do not to other people or projects. Don’t make fancy patterns in your comments so you can search for them later. Always consider that the code and comments represent both you and your company and will very likely be publicly available. The presence of flags, like BugBug, or ToDo statements indicating that comments should be added, reflect poorly upon the programmer.
Sections of code shall not be “commented out”.
Where sections of source code must not be compiled, use conditional compilation (such as #if or #ifdef constructs with a descriptive comment) to meet this requirement. C does not support nested comments, and the application of start and end comment markers to meet the requirement of source code that must not be compiled is a dangerous practice. This is because comments already existing in the section of code would change the outcome.
Do not comment out, or otherwise disable, previous revisions of the code.
Rely on your source control system to retain history, not your code.
Do not use the character sequence “/*” within a comment.
C does not support the nesting of comments, despite the existence of such support (as a language extension) within some compilers. Comment start with /* and end when the first */ is encountered.
</span></span>What You Must Comment
Comment function declarations if public, or implementations if private and not declared.
You must describe the purpose of the function and any side effects. Also describe the purpose or meaning of each parameter and return value.
Comment complicated, tricky, or sensitive pieces of code.
What the code is doing must be made clear. Making the code cleaner is often better than adding more comments.
Comment higher-level concepts in the code.
Focus on the why and not the how.
Comment data structure declarations and #define statements.
The include files should be sufficient to understand what data or code are for. It should not be necessary to search for all references to something to understand its purpose and use. If more than one instance of a structure or union is instantiated, comment each one as to its intended purpose. It should be clear from these comments why there are multiple instances and how each instance differs.
File comments should include the version number of the industry standard to which you are coding.
When possible, you should also list the requirements that are satisfied by the code.
</span></span>Types of Comments
Comments can be either global or internal.
</span></span></span></span>Global Comments
Global, or strategic, comments occur outside of function definitions and provide structural or algorithmic information about the file or program. Global comments are almost always special Doxygen comment blocks. See "Introducing Doxygen" on page 66.
Comments are allowed on structure member declarations:
typedef struct {
EFI_SAMPLE_STRUCTURE *StructurePointer; ///< Sample comment #1
UINT64 SimpleVariable; ///< Sample comment #2
} EFI_STRUCTURE_NAME;
</span></span></span></span>Internal Comments
Internal, or tactical, comments occur within the body of a function definition and are used to convey special information of use to someone actively reading the code. These comments are never special Doxygen comments.
For internal code comments, use C++ style (//) comment lines.
Include a blank line above a block of comment lines containing text.
These blank lines make comments visually distinct without relying on the editor.
A blank line may optionally follow a block of comments.
This should generally indicate that the comment is for a large block of code. No blank line implies that the comment is for the next few lines of code.
Comments are allowed on the parameters of a function call.
These comments provide supplemental information about the parameters for that specific function call. The information in parameter comments should not repeat the information in the descriptive text for the @param entries in the special documentation block describing the function. Function call parameter comments are never Doxygen comments.
Status = TestString (
String, // Comment for first parameter
Index + 3, // Comment for second parameter
&Value // Comment for third parameter
);
Indent the comments with the code.
This indentation conveys the scope of the comment, as well as maintaining readability of the code.
/// Do nothing, carefully.
void
NoFun (VOID)
{
// Only process data if mTest is TRUE.
// This comment block applies to the entire if/else statement.
if (mTest) {
// This is an example comment to explain why this behavior
// is appropriate if mTest is true.
// This comment block only applies when mTest is true.
ThisIsTheCode();
}
else {
// Explain what we do if (mTest) is false.
// This comment block only applies when mTest is false.
ThisIsMoreCode();
}
}
</span></span></span></span>Introducing Doxygen
Doxygen is a tool that allows one to generate documentation directly from a project’s source code. There are no complicated, specially formatted documentation tags required for one to get significant benefit from Doxygen. By simply adding an additional asterisk (*) or slash (/) to existing comments, they become special documentation blocks that Doxygen will add to any generated documentation. A few simple Doxygen commands allow the majority of special documentation tasks to be performed.
Please use Doxygen style comment blocks, at a minimum, when writing new code. If you have time, or are already making modifications, please update existing comments. You will be glad you did.
This document describes the Doxygen elements and style as it applies to EDK II. Other supported Doxygen tag and comment formats are to be eschewed in favor of the style documented here.
</span></span>How Doxygen Works
Doxygen understands the #include and #define preprocessor directives as well as the syntax of C and C++. Thus, Doxygen can generate documentation using just the existing syntactic elements of the source files, or one can supplement the syntactic documentation using "Special Documentation Blocks" on page 67. These special documentation blocks are just C or C++ comments with one or more special tags added.
For structures, unions, functions, and global data, you have two documentation options:
Place a special documentation block in front of the declaration or definition. For enum, structure, and union members, you are also allowed to place documentation directly after a member. See "Special Documentation Blocks" on page 67, to learn more about special documentation blocks.
Place a special documentation block somewhere else (another file or location) and put a structural command in the documentation block. A structural command links a documentation block to a certain entity that can be documented (e.g. a union, structure, function, or file).
The text inside a special documentation block is parsed before it is written to the output files. During parsing, the following steps take place:
The special commands inside the documentation block are executed.
If a line starts with some whitespace followed by one or more asterisks (*) and then optionally more whitespace, then all leading whitespace and asterisks are removed.
All resulting blank lines are treated as paragraph separators. This saves you from placing new-paragraph commands yourself in order to make the generated documentation readable.
Links to members are automatically created when certain patterns are found in the text. These patterns include: URLs and email addresses, names of documented classes and files, function and variable names, typedef, enum types, enum values, and defines.
HTML tags that are in the documentation are interpreted and converted to the proper equivalents for the selected output type.
</span></span></span></span></span>Special Documentation Blocks
A special documentation block is a C or C++ comment block with some additional markings, so that Doxygen knows it is a piece of documentation that needs to end up in the generated documentation.
Normally, Doxygen expects special documentation blocks to immediately precede the syntactic element being documented (Prefix). There is a mechanism to allow documentation to be placed after the element to be documented (Postfix). Prefix style comment blocks are described here, while postfix comment blocks are described in "Putting Documentation after Members" on page 68.
Each code item can have two types of descriptions. Together, a brief description and a detailed description form the documentation: Both are semantically optional. More than one brief or detailed description per code item, however, is not allowed. We require at least one of these descriptions to be present.
A brief description is short, usually a single line. A detailed description provides longer and more detailed documentation.
You may place these descriptions in a comment block in several ways:
- Comment blocks will automatically start a brief description which ends at the first period followed by a space or new line. For example:
/** Brief description which ends at this dot.
This sentence begins the detailed description. The detailed
description continues… */
- The behavior also exists for multi-line special C++ comments:
/// Brief description which ends at this dot.
/// This sentence begins the detailed description.
It is preferred that any special documentation block longer than two lines use C-style commenting as shown in the first example above. While not required by Doxygen, we require the blank line between the brief description and the detailed description.
Within the body of a C-style comment block, Doxygen will ignore any leading spaces and asterisks, ‘*’. This means that the first example could be rewritten as follows without any change in the generated documentation.
/** Brief description which ends at this dot.
*
* This sentence begins the detailed description. The detailed
* description continues… */
This type of comment decoration is acceptable because the line of ‘*’ along the left make it easier to determine the extent of the comment.
As you can see, Doxygen is quite flexible. For more information, see the full Doxygen documentation.
</span></span></span></span>Putting Documentation after Members
For example, to document the members of a struct, union, or enum, and to put the documentation for those members inside the compound, it might be desirable to place the documentation block after the member. Do this by putting an additional < marker in the comment block.
For example:
int var; ///< Brief description after the member
These blocks have the same structure and meaning as special comment blocks. The < indicates that the member to be documented is located before the comment.
Only be used these blocks to document members and parameters. Do not use them to document files, classes, unions, structs, groups, namespace, or enums themselves. Furthermore, structural commands (such as @struct) are ignored inside these comment blocks.
</span></span></span></span>Special Commands
All Doxygen commands start with an “at” sign (@). A commands may have one or more arguments. The following typographic conventions are used to identify each arguments range:
If <sharp> braces are used, the argument is a single word.
If (round) braces are used, the argument extends until the end of the line on which the command was found.
If {curly} braces are used, the argument extends until the next paragraph. Paragraphs are delimited by a blank line or by a section indicator.
If [square] brackets are used, the argument is optional.
The following sections describe the special Doxygen commands.
</span>@example <file-name>
Indicates that a comment block contains documentation for a source code example.
</span>@file [<name>]
Indicates that a comment block contains documentation for a source or header file with name <name>. If the file name is omitted, Doxygen uses the name of the file that contains the @file command. This is the preferred method.
</span>@attention { attention text }
Starts an indented paragraph where you can enter a message about an issue that needs attention.
</span>@param[in,out] <parameter-name> { parameter description }
Starts a parameter description for a function parameter named <parameter-name>.
</span>@post { description of a postcondition }
Starts an indented paragraph where you can describe a postcondition of an entity.
</span>@pre { description of a precondition }
Starts an indented paragraph where you can describe a precondition of an entity.
</span>@retval <return value> { description }
Starts a description of a return value from a function. Include a separate @retval for each unique return value.
</span>@return { description of what is returned }
Starts a description for a function’s return values when those values aren’t easily described by @retval commands (that is, the return values are something other than a small set of unique values with discrete meanings).
</span>@sa { references }
Starts a paragraph where you can specify one or more cross-references to functions, structures, variables, files, or URLs.
</span>@since { text }
This tag can be used to specify when (version or time) an entity is available.
</span>@test { paragraph describing a test case }
Starts a paragraph where you can describe a test case. The description will also add the test case to a separate test list. The two instances of the description will be cross-referenced. Each test case in the test list will be preceded by a header that indicates the origin of the test case.
</span>@todo { paragraph describing what is to be done }
Starts a paragraph where a TODO item is described. The description will also add an item to a separate TODO list. The two instances of the description will be cross-referenced. Each item in the TODO list will be preceded by a header that indicates the origin of the item.
</span>HTML Commands
For greater control over the format of generated documentation, you may add HTML commands to special documentation blocks. "HTML Character Entities" below lists the special HTML character entities that Doxygen recognizes.
"HTML Commands" on page 71 lists the HTML commands that you may use inside the documentation.
Finally, to put invisible comments inside comment blocks, you may use HTML style comments:
/** <!-- This is a comment within a comment block --> Visible text */
</span>Table 2 - 1. HTML Character Entities
Entity | Description |
© | Copyright symbol |
&tm; | Trade mark symbol |
® | Registered trade mark symbol |
< | Less-than symbol |
> | Greater-than symbol |
& | Ampersand |
' | Single quotation mark (straight) |
" | Double quotation mark (straight) |
‘ | Left single quotation mark |
’ | Right single quotation mark |
“ | Left double quotation mark |
” | Right double quotation mark |
– | En-dash (for numeric ranges, e.g. 2–8) |
— | Em-dash (for parenthetical punctuation—like this) |
&?uml; | Where ? is one of {A,E,I,O,U,Y,a,e,i,o,u,y}, writes a character with a diaeresis accent (ä). |
&?acute; | Where ? is one of {A,E,I,O,U,Y,a,e,i,o,u,y}, writes a character with an acute accent (á). |
&?grave; | Where ? is one of {A,E,I,O,U,a,e,i,o,u,y}, writes a character with a grave accent (à). |
&?circ; | Where ? is one of {A,E,I,O,U,a,e,i,o,u,y}, writes a character with a circumflex accent (â). |
&?tilde; | Where ? is one of {A,N,O,a,n,o}, writes a character with a tilde accent (ã). |
ß | Sharp s (ß). |
&?cedil; | Where ? is one of {c,C}, writes a c-cedille (ç). |
&?ring; | Where ? is one of {a,A}, writes an ‘a’ with a ring (å). |
A non breaking space. |
</span>
</span>Table HTML Commands
Command | Description |
<A HREF="..."> | Starts an HTML hyper-link. |
<A NAME="..."> | Starts a named anchor. |
</A> | Ends a link or anchor. |
<B> | Starts a piece of text displayed in a bold font. |
</B> | Ends a <B> section. |
<BODY> | Does not generate any output. |
</BODY> | Does not generate any output. |
<BR> | Forces a line break. |
<CENTER> | Starts a section of centered text. |
</CENTER> | Ends a section of centered text. |
<CAPTION> | Starts a caption. Use within a table only. |
</CAPTION> | Ends a caption. Use within a table only. |
<CODE> | Starts a piece of text displayed in a typewriter font. |
</CODE> | End a <CODE> section. |
<DD> | Starts an item description. |
<DFN> | Starts a piece of text displayed in a typewriter font. |
</DFN> | Ends a <DFN> section. |
<DIV> | Starts a section with a specific style |
</DIV> | Ends a section with a specific style |
<DL> | Starts a description list. |
</DL> | Ends a description list. |
<DT> | Starts an item title. |
</DT> | Ends an item title. |
<EM> | Starts a piece of text displayed in an italic font. |
</EM> | Ends a <EM> section. |
<FORM> | Does not generate any output. |
</FORM> | Does not generate any output. |
<HR> | Writes a horizontal rule. |
<H1> | Starts an unnumbered section. |
</H1> | Ends an unnumbered section. |
<H2> | Starts an unnumbered subsection. |
</H2> | Ends an unnumbered subsection. |
<H3> | Starts an unnumbered sub subsection. |
</H3> | Ends an unnumbered sub subsection. |
<I> | Starts a piece of text displayed in an italic font. |
<INPUT> | Does not generate any output. |
</I> | Ends a <I> section. |
<IMG> | This command is written with attributes to the HTML output. |
<LI> | Starts a new list item. |
</LI> | Ends a list item. |
<META> | Does not generate any output. |
<MULTICOL> | Ignored by Doxygen. |
</MUTLICOL> | Ignored by Doxygen. |
<OL> | Starts a numbered item list. |
</OL> | Ends a numbered item list. |
<P> | Starts a new paragraph. |
</P> | Ends a paragraph. |
<PRE> | Starts a pre-formatted fragment. |
</PRE> | Ends a pre-formatted fragment. |
<SMALL> | Starts a section of text displayed in a smaller font. |
</SMALL> | Ends a <SMALL> section. |
<SPAN> | Starts an inline text fragment with a specific style. |
</SPAN> | Ends an inline text fragment with a specific style. |
<STRONG> | Starts a section of bold text. |
</STRONG> | Ends a section of bold text. |
<SUB> | Starts a piece of text displayed in subscript. |
</SUB> | Ends a <SUB> section. |
<SUP> | Starts a piece of text displayed in superscript. |
</SUP> | Ends a </SUP> section. |
<TABLE> | Starts a table. |
</TABLE> | Ends a table. |
<TD> | Starts a new table data element. |
</TD> | Ends a table data element. |
<TR> | Starts a new table row. |
</TR> | Ends a table row. |
<TT> | Starts a piece of text displayed in a typewriter font. |
</TT> | Ends a <TT> section. |
<KBD> | Starts a piece of text displayed in a typewriter font. |
</KBD> | Ends a <KBD> section. |
<UL> | Starts an unnumbered item list. |
</UL> | Ends an unnumbered item list. |
<VAR> | Starts a piece of text displayed in an italic font. |
</VAR> | Ends a </VAR> section. |
</span></span>APPENDIX A
Common Examples
</span></span>File Heading
/** @file
Brief description of file’s purpose.
Detailed description of file’s purpose.
Copyright (c) 2006 - 2014, Acme Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
of the BSD License which accompanies this distribution. The full
text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Specification Reference:
UEFI 2.3, Chapter 9, Device Path Protocol
PI 1.1, Chapter 10, Boot Paths
**/
#ifndef FOO_BAR_H_
#define FOO_BAR_H_
// Body of the file goes here
#endif // FOO_BAR_H_
</span></span>Function Declarations
/** Brief description of this function’s purpose.
Follow it immediately with the detailed description.
@param[in] Arg1 Description of Arg1.
@param[in] Arg2 Description of Arg2. This is complicated
and requires multiple lines to describe.
@param[out] Arg3 Description of Arg3.
@param[in, out] Arg4 Description of Arg4.
@retval VAL_ONE Description of what VAL_ONE signifies.
@retval OTHER This is the only other return value. If there
were other return values, they would be listed.
**/
EFI_STATUS
EFIAPI
FooBar (
IN UINTN Arg1,
IN UINTN Arg2, OPTIONAL
OUT UINTN *Arg3,
IN OUT UINTN *Arg4
);
</span></span>Type Declarations
/// Brief description of this enum.
/// Detailed description if justified.
typedef enum {
EnumMenberOne, ///< First member description.
EnumMemberTwo, ///< Second member description.
EnumMemberMax ///< Number of members in this enum.
} ENUMERATE_TYPE;
/// Structure without forward reference.
typedef struct {
UINT32 Signature; ///< Signature description.
EFI_HANDLE Handle; ///< Handle description.
EFI_PROD_PROT1_PROTOCOL ProdProt1; ///< ProdProt1 description.
EFI_PROD_PROT2_PROTOCOL ProdProt2; ///< ProdProt2 description.
} DRIVER_NAME_INSTANCE;
/// Self referential Structure.
typedef struct EFI_CPU_IO_PROTO {
struct EFI_CPU_IO_PROTO *Mem;
EFI_CPU_IO_PROTOCOL_ACCESS Io;
} EFI_CPU_IO_PROTOCOL;
/// Forward reference
typedef struct StructTag MyStruct;
/// Forward reference target
struct StructTag {
INT32 First;
INT32 Second;
};
</span></span>Function Calling
Status = TestString ();
Status = TestString (String, Index + 3, &Value);
Status = TestString (
String,
Index + 3,
&Value
);
</span></span>Control Statements
if (Test && !Test2) {
// This is an example comment to explain why this behavior
// is appropriate.
IamTheCode ();
} else if (Test2) {
// This is an example comment to explain why this behavior
// is appropriate.
IamTheCode ();
} else {
// This is an example comment to explain why this behavior
// is appropriate.
IamTheCode ();
}
while (TRUE) {
IamTheCode ();
}
do {
IamTheCode ();
} while (TRUE);
for (Index = 0; Index < MAX_INDEX; Index++) {
IamTheCode (Index);
}
switch (Variable) {
case 1:
IamTheCode ();
break;
case 2:
IamTheCode ();
break;
default:
IamTheCode ();
break;
};
</span></span></span>APPENDIX B
Reserved Identifiers
__bool_true_false_are_defined | _Complex_I | _Exit |
_IOFBF | _IOLBF | _IONBF |
abort | acos | acosf |
acoshf | acoshl | acosl |
and_eq | asctime | asin |
asinh | asinhf | asinhl |
assert | atan | atan2 |
atan2l | atanf | atanh |
atanhl | atanl | atexit |
atoi | atol | atoll |
bitand | bitor | bool |
btowc | cabs | cabsf |
cacos | cacosf | cacosh |
cacoshf | cacoshl | calloc |
cargf | cargl | casin |
casinl | casinh | casinhf |
catan | catanf | catanl |
catanhf | catanhl | cbrt |
cbrtl | ccos | ccosf |
ccoshf | ccoshl | ccosl |
ceilf | ceill | cexp |
cexpl | CHAR_BIT | CHAR_MIN |
cimag | cimagf | cimagl |
clock | clock_t | CLOCKS_PER_SEC |
clogf | clogl | compl |
conj | conjf | conjl |
copysignf | copysignl | cos |
cosl | cosh | coshf |
cpow | cpowf | cpowl |
cprojf | cprojl | creal |
creall | csin | csinf |
csinhf | csinhl | csinl |
csqrtf | csqrtl | ctan |
ctanl | ctanh | ctanhf |
ctime | CX_LIMITED_RANGE | DBL_DIG |
DBL_MAX | DBL_MANT_DIG | DBL_MAX_10_EXP |
DBL_MIN | DBL_MIN_10_EXP | DBL_MIN_EXP |
difftime | div | div_t |
EDOM | EILSEQ | EOF |
erf | erff | erfl |
erfcf | erfcl | errno |
EXIT_FAILURE | EXIT_SUCCESS | exp |
expl | exp2 | exp2f |
expm1 | expm1f | expm1l |
fabsf | fabsl | false |
fdim | fdimf | fdiml |
FE_DFL_ENV | FE_DIVBYZERO | FE_DOWNWARD |
FE_INVALID | FE_OVERFLOW | FE_TONEAREST |
FE_UNDERFLOW | FE_UPWARD | feclearexcept |
fegetexceptflag | feholdexcept | fegetround |
FENV_ACCESS | fenv_t | feraiseexcept |
fesetenv | fesetexceptflag | fesetround |
feupdateenv | fexcept_t | fflush |
fgetpos | fgetwc | fgetws |
FILE | FILENAME_MAX | float_t |
floorf | floorl | FLT_DIG |
FLT_EVAL_METHOD | FLT_MANT_DIG | FLT_MAX |
FLT_MAX_EXP | FLT_MIN | FLT_MIN_10_EXP |
FLT_RADIX | FLT_ROUNDS | fma |
fmax | fmaxf | fmaxl |
fminf | fminl | fmod |
fmodl | fopen | FOPEN_MAX |
FP_FAST_FMA | FP_FAST_FMAF | FP_FAST_FMAL |
FP_ILOGBNAN | FP_INFINITE | FP_NAN |
FP_SUBNORMAL | FP_ZERO | fpclassify |
fputs | fpos_t | fprintf |
fputws | fread | free |
frexp | frexpf | frexpl |
fseek | fsetpos | ftell |
fwprintf | fwrite | fwscanf |
getchar | getenv | gets |
getwchar | gmtime | HUGE_VAL |
HUGE_VALL | hypot | hypotf |
I | ilogb | ilogbf |
imaginary | imaxdiv_t | imaxabs |
INFINITY | INT_FASTN_MIN | INT_FASTN_MAX |
INT_LEASTN_MIN | INT_LEASTN_MAX | int_leastN_t |
INT_MIN | INTMAX_C | INTMAX_MAX |
intmax_t | INTN_C | INTN_MIN |
intN_t | intptr_t | INTPTR_MIN |
isalnum | isalpha | isblank |
isdigit | isfinite | isgraph |
isgreaterequal | isinf | isless |
islessgreater | islower | isnan |
isprint | ispunct | isspace |
isupper | iswalnum | iswalpha |
iswcntrl | iswctype | iswdigit |
iswlower | iswprint | iswpunct |
iswupper | iswxdigit | isxdigit |
L_tmpnam | labs | LC_ALL |
LC_CTYPE | LC_MONETARY | LC_NUMERIC |
LDBL_DIG | LDBL_EPSILON | LDBL_MANT_DIG |
LDBL_MAX_EXP | LDBL_MAX_10_EXP | LDBL_MIN |
LDBL_MIN_10_EXP | ldexp | ldexpf |
ldiv | ldiv_t | lgamma |
lgammal | llabs | lldiv |
LLONG_MAX | LLONG_MIN | llrint |
llrintl | llround | llroundf |
localeconv | localtime | log |
logl | log10 | log10f |
log1p | log1pf | log1pl |
log2f | log2l | logb |
logbl | LONG_MAX | LONG_MIN |
lrint | lrintf | lrintl |
lroundf | lroundl | mal |
MATH_ERREXCEPT | math_errhandling | MATH_ERRNO |
MB_LEN_MAX | mblen | mbrlen |
mbsinit | mbstate_t | mbstowcs |
mbtowc | memchr | memcmp |
memmove | memset | mktime |
modff | modfl | NAN |
nanf | nanl | NDEBUG |
nearbyintf | nearbyintl | nextafter |
nextafterl | nexttoward | nexttowardf |
not | not_eq | NULL |
or_eq | offsetof | perror |
powf | powl | PRIdN |
PRIoN | PRIuN | PRIXN |
PRIdLEASTN | PRIdFASTN | PRIdMAX |
PRIiLEASTN | PRIiFASTN | PRIiMAX |
printf | PRIoLEASTN | PRIoFASTN |
PRIoPTR | PRIuLEASTN | PRIuFASTN |
PRIuPTR | PRIXLEASTN | PRIxLEASTN |
PRIxFASTN | PRIXMAX | PRIxMAX |
PRIxPTR | PTRDIFF_MAX | PTRDIFF_MIN |
putc | putchar | puts |
putwchar | qsort | raise |
RAND_MAX | realloc | remainder |
remainderl | remove | remquo |
remquol | rename | rewind |
rintf | rintl | round |
roundl | scalbn | scalbnf |
scalbln | scalblnf | scalblnl |
SCHAR_MAX | SCHAR_MIN | SCNdN |
SCNdLEASTN | SCNdMAX | SCNdPTR |
SCNiFASTN | SCNiLEASTN | SCNiMAX |
SCNoN | SCNoFASTN | SCNoLEASTN |
SCNoPTR | SCNuN | SCNuFASTN |
SCNuMAX | SCNuPTR | SCNxN |
SCNxLEASTN | SCNxMAX | SCNxPTR |
SEEK_END | SEEK_SET | setbuf |
setlocale | setvbuf | SHRT_MAX |
SIG_ATOMIC_MAX | SIG_ATOMIC_MIN | sig_atomic_t |
SIG_ERR | SIG_IGN | SIGABRT |
SIGILL | SIGINT | signal |
SIGSEGV | SIGTERM | sin |
sinl | sinh | sinhf |
SIZE_MAX | size_t | snprintf |
sqrt | sqrtf | sqrtl |
sscanf | stderr | stdin |
strcat | strchr | strcmp |
strcpy | strcspn | strerror |
strlen | strncat | strncmp |
strpbrk | strrchr | strspn |
strtod | strtof | strtoimax |
strtol | strtold | strtoll |
strtoull | strtoumax | strxfrm |
swscanf | system | tan |
tanl | tanh | tanhf |
tgamma | tgammaf | tgammal |
time_t | TMP_MAX | tmpfile |
tolower | toupper | towlower |
towctrans | true | trunc |
truncl | UCHAR_MAX | UINT_FASTN_MAX |
UINT_LEASTN_MAX | uint_leastN_t | UINT_MAX |
UINTMAX_MAX | uintmax_t | UINTN_C |
uintN_t | UINTPTR_MAX | uintptr_t |
ULONG_MAX | ungetc | ungetwc |
va_arg | va_copy | va_end |
va_start | vfprintf | vfscanf |
vfwscanf | vprintf | vscanf |
vsprintf | vsscanf | vswprintf |
vwprintf | vwscanf | WCHAR_MAX |
wchar_t | wcscat | wcschr |
wcscoll | wcscpy | wcscspn |
wcslen | wcsncat | wcsncmp |
wcspbrk | wcsrchr | wcsrtombs |
wcsstr | wcstod | wcstof |
wcstok | wcstol | wcstold |
wcrtomb | wcstombs | wcstoul |
wcstoumax | wcsxfrm | wctob |
wctrans | wctrans_t | wctype |
WEOF | WINT_MAX | WINT_MIN |
wmemchr | wmemcmp | wmemcpy |
wmemset | wprintf | wscanf |
xor_eq | _Imaginary_I |
</span></span></span>APPENDIX C
Optimization and Performance
You might be tempted to use all sorts of clever techniques to optimize the code. However, this optimization comes at a penalty.
Rob Pike provides these comments on program complexity (http://www.lysator.liu.se/c/pikestyle.html Notes on Programming in C):
“Most programs are too complicated — that is, more complex than they need to be to solve their problems efficiently . . . But programs are often complicated at the microscopic level . . .”
The following are also condensed from Mr. Pike’s 1989 Notes on Programming in C:
Rule 1. Don’t guess at optimization
- Prove the bottleneck location, then put in a speed hack.
Rule 2. Measure before tuning for speed
- Be judicious. Only tune for speed if absolutely necessary.
Rule 3. Use simple algorithms
- Fancy algorithms are slow.
Rule 4. Use simple data structures.
Pike believes that these data structures are almost always enough:
array
linked list
hash table
binary tree
Rule 5. Data structures are central to programming; algorithms are not.