progmasoft-cpp
The C++ style guide of Progmasoft: naming, formatting, language rules, errors, ownership, ABI, testing and tooling.
Clonegit clone https://git.progmasoft.com/progmasoft-cpp
Write Progmasoft Core C Coding Guidelines
- Commit
fec4661eee5ef6548f9d914a409a496251efcb39- Author
- Leitwolf11 ·
- Parents
f57d68b8ec3d
Changes
ADOPTING.md | 6 + CHANGELOG.md | 4 + LICENSE.md | 2 +- Progmasoft_Core_C_Coding_Guidelines/.gitkeep | 0 Progmasoft_Core_C_Coding_Guidelines/C11/.gitkeep | 0 .../C11/COMMENTS-AND-DOCUMENTATION.md | 63 ++++++ .../C11/CONTROL-FLOW.md | 77 +++++++ .../C11/DECLARATIONS-AND-INITIALIZERS.md | 81 +++++++ .../C11/FILES-AND-HEADERS.md | 57 +++++ .../C11/FORMATTING.md | 251 +++++++++++++++++++++ .../C11/LANGUAGE.md | 31 +++ .../C11/MEMORY-AND-OWNERSHIP.md | 102 +++++++++ Progmasoft_Core_C_Coding_Guidelines/C11/NAMING.md | 122 ++++++++++ .../C11/PREPROCESSOR.md | 45 ++++ .../C11/PRINCIPLES.md | 42 ++++ Progmasoft_Core_C_Coding_Guidelines/C11/TOOLING.md | 67 ++++++ Progmasoft_Core_C_Coding_Guidelines/index.json | 39 ++++ README.md | 40 +++- 18 files changed, 1027 insertions(+), 2 deletions(-) diff --git a/ADOPTING.md b/ADOPTING.md index e6673dc..07579bb 100644 --- a/ADOPTING.md +++ b/ADOPTING.md @@ -59,6 +59,12 @@ Existing code is not rewritten in one sweep. A file follows the guidelines where change, such as applying `clang-format` to a directory or renaming a member convention, is its own pull request, never mixed with a change in behavior, so that review and `git blame` stay useful. +## C projects + +A C project adopts [Progmasoft Core C Coding Guidelines](Progmasoft_Core_C_Coding_Guidelines/C11/PRINCIPLES.md) the same way: it points to them in its +contributing guide, copies [the `.clang-format` profile](Progmasoft_Core_C_Coding_Guidelines/C11/FORMATTING.md#the-profile) and [the `.clang-tidy` +profile](Progmasoft_Core_C_Coding_Guidelines/C11/TOOLING.md#111-the-clang-tidy-profile), and records its deviations. + ## Projects that follow the guidelines | Project | Deviations recorded in | diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fb3c39..aaa8e3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ A revision of Progmasoft C/C++ Styles is named by its date. A change that requir ## Unreleased +Progmasoft Core C Coding Guidelines are written, for C11 with LLVM 23, in +`Progmasoft_Core_C_Coding_Guidelines/C11/`: eleven chapters, a `.clang-format` and a `.clang-tidy` profile, and an +`index.json`. They are a style of their own; the C interfaces of C++ libraries keep following the C++ guidelines. + `index.json` names its JSON Schema, [schemastore.progmasoft.com/json/progmasoft-cpp-index.json](https://schemastore.progmasoft.com/json/progmasoft-cpp-index.json), in `$schema`; editors check the file against it. diff --git a/LICENSE.md b/LICENSE.md index 1e7efac..f3bb1d8 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -14,7 +14,7 @@ the license and say whether you changed it. A credit line such as this one is en **Configuration and code examples are dedicated to the public domain** under [CC0 1.0 Universal](LICENSES/CC0-1.0.md). This covers every fenced code block in this repository: the `.clang-format` -and `.clang-tidy` profiles, the compiler flags, and the C++ examples. Copy them into your own projects without credit +and `.clang-tidy` profiles, the compiler flags, and the C and C++ examples. Copy them into your own projects without credit and under any license. The legal code of CC BY 4.0 follows. The legal code of CC0 is in [LICENSES/CC0-1.0.md](LICENSES/CC0-1.0.md). diff --git a/Progmasoft_Core_C_Coding_Guidelines/.gitkeep b/Progmasoft_Core_C_Coding_Guidelines/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/.gitkeep b/Progmasoft_Core_C_Coding_Guidelines/C11/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/COMMENTS-AND-DOCUMENTATION.md b/Progmasoft_Core_C_Coding_Guidelines/C11/COMMENTS-AND-DOCUMENTATION.md new file mode 100644 index 0000000..98a8ea1 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/COMMENTS-AND-DOCUMENTATION.md @@ -0,0 +1,63 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 10. Comments and documentation + +## 10.1 Comments + +- **Comments should be `/* ... */`.** `//` is not forbidden, but should not be the choice. +- **A comment over several lines has a `*` at the start of each line.** +- **A comment stands above the code it explains, at the same indentation.** Comments at the end of a line are not used. +- **The project chooses the language of its comments and documentation**, and its own markers such as `TODO` and + `FIXME`. + +## 10.2 Doxygen + +- **Every function is documented with Doxygen**: public, internal and `static` ones. A function that has a declaration + and a definition is documented at both. +- **Commands start with `@`**, never `\`: `@brief`, not `\brief`. +- **`@brief` is one short sentence.** More detail, when needed, goes into a paragraph of its own. +- **Parameters are documented in the order of the signature**, with their direction: `@param[in]`, `@param[out]`, + `@param[in,out]`. A plain value parameter is `@param[in]`. The names and the descriptions of the `@param` lines line + up. +- **A function that returns a value documents it** with `@return`, or `@retval` for each value that has a meaning of + its own. A `void` function has neither. +- **Every sentence of the documentation ends with a full stop.** +- **`@note` is information without risk, `@remark` a behavior that matters, `@warning` a serious risk.** +- **`@pre`, `@post`, `@see` and `@todo` may be used where they help; a deprecated interface has `@deprecated`.** +- **Code in the documentation**: a C block over several lines should be `@code{.c}` ... `@endcode`; a short piece may be + `@c`. +- **Not used**: `@since`, `@version`, `@author`, `@file`, `@ingroup`, `@details`. + +## 10.3 The order of a comment + +The parts come in this order; a part that is not needed is left out: + +1. `@brief` +2. the paragraph with the details +3. `@param` +4. `@return` or `@retval` +5. `@pre` and `@post` +6. `@note`, `@remark` and `@warning` +7. `@todo` +8. `@deprecated` +9. `@see` + +`@param` and `@return` lines stand together, with no blank line between them; other parts may be separated by an empty +` *` line. + +```c +/** + * @brief Copies values into a destination buffer. + * + * @param[out] aOut_pDestination Destination array. + * @param[in] aIn_pSource Source array. + * @param[in] aCount Number of elements. + * @return true on success, false otherwise. + * + * @pre The source and the destination do not overlap. + * @see Example_List_Append() + */ +bool +Example_CopyValues(int* aOut_pDestination, const int* aIn_pSource, size_t aCount); +``` diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/CONTROL-FLOW.md b/Progmasoft_Core_C_Coding_Guidelines/C11/CONTROL-FLOW.md new file mode 100644 index 0000000..47a1f10 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/CONTROL-FLOW.md @@ -0,0 +1,77 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 5. Control flow + +## 5.1 Conditions + +- **A Boolean is tested directly**: `if(isReady)`, `if(!isReady)`; never `== true` or `== false`. +- **A pointer is compared with `NULL`**: `pData == NULL`, `pData != NULL`. The null pointer constant is `NULL`, never + `0`. +- **A condition assigns nothing**: no `=`, `+=` or other assignment inside it. +- **The variable stands left of the constant**: `count == 0`, not `0 == count`. +- **A ternary is never nested.** A simple one may be used; when it does not fit on one line, `?` and `:` start their + lines. + +## 5.2 Returning + +- **A function may return from several places.** +- **A returned value is written in parentheses**: `return(expression);`. +- **A `void` function may return early with `return;`**, but should not end with one. + +## 5.3 Loops + +- **A `for` loop should step with postfix `index++` or `index--`.** Elsewhere, choose prefix or postfix by meaning. An + increment inside a larger expression should be its own statement. +- **An empty loop body is `{ }`**, never a bare `;`. +- **The empty parts of a `for` stay visible**: `for(; isRunning;)`, `for(;;)`. + +## 5.4 `switch` + +- **Every `switch` has a `default`, and it comes last.** +- **`case` and `default` start in the column of the `switch`.** +- **`case` labels that share a body may follow each other**, each on its own line. +- **No blank line follows a `case` label; one blank line separates two `case` groups.** +- **A `case` may have its own block**, `{ }`, when it needs local variables. +- **A deliberate fall-through is marked `/* Fall through. */`.** Adjacent labels that share a body need no mark. + +```c +switch(state) +{ +case kPending: +case kWaiting: + ProcessPending(); + break; + +case kRunning: + ProcessEvents(); + break; + +default: + break; +} +``` + +## 5.5 `goto` + +- **`goto` jumps only to the point that handles an error or releases resources.** +- **A label is `gotoPascalCase`**, starts in the first column, and has one blank line before it and none after it. + +```c +int +FillBuffer(size_t aSize) +{ + int result = -1; + + int* pBuffer = malloc(aSize); + + if(pBuffer == NULL) + goto gotoFailed; + + result = Fill(pBuffer, aSize); + +gotoFailed: + free(pBuffer); + return(result); +} +``` diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/DECLARATIONS-AND-INITIALIZERS.md b/Progmasoft_Core_C_Coding_Guidelines/C11/DECLARATIONS-AND-INITIALIZERS.md new file mode 100644 index 0000000..c01e9b3 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/DECLARATIONS-AND-INITIALIZERS.md @@ -0,0 +1,81 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 6. Declarations and initializers + +## 6.1 Declarations + +- **Each pointer variable is declared on its own line.** Related variables that are not pointers may share a line; + unrelated ones do not. +- **A variable should be declared where it is first used, and initialized there.** It should not be set to zero or + `NULL` only to be overwritten; it must hold a valid value before it is first read. +- **Declarations are grouped by type**, with a blank line between two groups, and a blank line separates the + declarations at the start of a block from the work that follows them. +- **A unary operation should be parenthesized where that reads more clearly**: `(-3) + (-2)`. A unary `+` that changes + nothing is left out. + +```c +size_t total = 0U; +size_t count = Example_List_Count(aIn_pList); + +const int* pValues = Example_List_Values(aIn_pList); + +for(size_t index = 0U; index < count; index++) + total += (size_t) pValues[ index ]; +``` + +## 6.2 Types + +- **A `typedef` of a `struct`, `union` or `enum` keeps its tag**: `typedef struct Example_List_List { ... } + Example_List_tList;`. +- **A forward declaration is `typedef struct Tag tType;`**: `typedef struct Example_List_List Example_List_tList;`. +- **The parameter names of a function pointer `typedef` are optional.** When they are written, they follow the rules for + parameters ([Naming](NAMING.md#33-parameters)). +- **A function without parameters says `(void)`**, in its declaration, its definition and a function pointer type. + +## 6.3 Literals + +- **Hexadecimal literals have a lowercase `0x` and uppercase digits**: `0xFF00AAU`. +- **Suffixes are uppercase**: `U`, `L`, `LL`, `F`. A literal should carry the suffix of its real type: `0.5F` for a + `float`, `1024U` for an unsigned value. +- **Scientific notation uses a lowercase `e`**: `1.5e+10`. +- **A decimal point has a digit on each side**: `0.5`, `2.0`, never `.5` or `2.`. +- **No octal literals**, and no leading zeros on decimal ones: `010` is eight, which nobody means. +- **Characters are escaped as `\n` and `\t`; the null character is `\x00`.** +- **A long string is split into adjacent literals**, lined up under the first one. A string never continues over a line + with `\`. + +```c +float ratio = 0.5F; +unsigned int flags = 0xFF00AAU; +double magnitude = 1.5e+10; +const char* pText = "First part " + "second part."; +``` + +## 6.4 Initializers + +- **A short list may stand on one line**: `{ 1, 2, 3 }`. +- **A list over several lines opens with `{` on the line of the assignment**, indents its items by eight spaces and + closes with `}` on a line of its own. +- **A list over several lines has a comma after its last item**: an `enum`, and an array, `struct`, `union` or + compound literal initializer. A list on one line has none. The comma keeps the list over several lines when + `clang-format` runs, and adding an item then changes one line of a diff, not two. +- **Designated initializers are used only where choosing the member is the point**, such as a `union` or a sparse + table. +- **Zero initialization is `{ 0 }`.** `{}` is not C11. + +```c +int values[ 3 ] = { 1, 2, 3 }; + +int numbers[] = { + 10, + 20, + 30, +}; + +Example_tUserData data = { 0 }; +``` + +`clang-format` puts the comma after the last enumerator itself (`EnumTrailingComma: Insert` in +[the profile](FORMATTING.md#the-profile)); in an initializer, the author writes it. diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/FILES-AND-HEADERS.md b/Progmasoft_Core_C_Coding_Guidelines/C11/FILES-AND-HEADERS.md new file mode 100644 index 0000000..fc51ce6 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/FILES-AND-HEADERS.md @@ -0,0 +1,57 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 4. Files and headers + +## 4.1 File and directory names + +- **A file is named after its module**, the parts of the module name in `PascalCase` joined by dots: + `Example.List.h`, `Example.List.Builder.h`. +- **A directory is optional; when there is one, it is the first part of the module name in lowercase**, with no + separators: `example/Example.List.h`. Both `Example.List.h` and `example/Example.List.h` are right; + `example/Other.Core.h` is wrong, because the directory and the module disagree. +- **Names are compared without regard to case.** Two files or directories whose names differ only in case collide on + some file systems, so a project must not have them. +- **An umbrella header, which includes the whole module, should end in `.Foundation.h`**: + `example/Example.Foundation.h`. + +## 4.2 The start of a header + +- **Every header starts with `#pragma once`.** Include guard macros are not used. +- **A public header wraps its declarations in a conditional `extern "C"` block**, so that a C++ caller links against + the C names. The block is active only when a C++ compiler reads the header. + +```c +#pragma once + +#include <stdbool.h> +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* The declarations of the module. */ + +#ifdef __cplusplus +} +#endif +``` + +## 4.3 Includes + +- **The groups come in a fixed order**: the C standard library, then third-party libraries, then the project's own + headers. One blank line separates the groups, and each group is sorted alphabetically. +- **Standard and third-party headers are included with `<...>`**; the project's own with `"..."`, by the path of the + module: `"example/Example.List.h"`. + +```c +#include <stdint.h> +#include <stdlib.h> + +#include <zlib.h> + +#include "example/Example.List.h" +``` + +The profile in [Formatting](FORMATTING.md#the-profile) sorts and groups includes this way. diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/FORMATTING.md b/Progmasoft_Core_C_Coding_Guidelines/C11/FORMATTING.md new file mode 100644 index 0000000..68367d6 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/FORMATTING.md @@ -0,0 +1,251 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 2. Formatting + +`clang-format` with the profile below does most of the layout. The rules in this chapter are the layout itself; the +profile applies them where `clang-format` 23 can, and [What the tool leaves to you](#what-the-tool-leaves-to-you) lists +the rest. + +## The shape of the code + +```c +int +CalculateResult(int aFirstValue, int aSecondValue) +{ + if(aFirstValue < 0) + return(-1); + + return(aFirstValue + aSecondValue); +} + +void +NoOperation(void) +{ } +``` + +## 2.1 Indentation and lines + +- **Indent by eight spaces**, never by tabs. +- **Code and comments end by column 100.** +- **A continuation line is indented by eight spaces.** +- **Exactly one blank line between two functions.** + +## 2.2 Functions and braces + +- **The return type stands on its own line**, above the function name, in declarations and definitions. +- **The opening brace of a function, `struct`, `union`, `enum`, `if`, `for`, `while`, `switch` and `do` stands on its + own line.** +- **`else` and the `while` of a `do` follow the closing brace**: `} else`, `} else if(`, `} while(`. +- **An empty body is `{ }` on the line after its head**: `NoOperation(void)` above, `for(;;)` then `{ }`, and `do`, + then `{ } while(condition);`. + +## 2.3 Bodies with one statement + +- **A body of one statement has no braces**, and the statement stands on the next line. A body of more than one + statement has braces. +- **The `if` and the `else` of a statement are judged separately**: one may have braces while the other has none. + +```c +if(aIsReady) +{ + values[ 0 ] = aValue; + gsCounter++; +} else if(aValue > 0) + values[ 1 ] = aValue; +else + values[ 2 ] = 0; +``` + +## 2.4 Parentheses and spaces + +- **No space between `if`, `for`, `while` or `switch` and its `(`**: `if(`, `else if(`, `switch(state)`. +- **`return` with a value writes it in parentheses**: `return(result);`. A `void` function may return early with + `return;`. +- **One space after each comma.** +- **Binary arithmetic, bitwise, comparison and assignment operators have a space on each side.** A unary operator (`!`, + `~`, `+`, `-`, `*`, `&`, `++`, `--`) sticks to its operand. +- **A cast is `(Type) expression`**, with one space; `sizeof` is `sizeof(expression)`. A compound literal has no space + between `)` and `{`: `(Example_tUserData){ 0 }`. +- **No space around `.` and `->`.** +- **Square brackets have one space inside**, in declarations and in indexing: `values[ 10 ]`, `values[ index ]`. +- **The `*` of a pointer sticks to the type**: `int* pValue`. + +## 2.5 Breaking long lines + +- **Parameters and arguments that do not fit on one line each get a line of their own**, the first one right after the + `(` and the others in the column of the first. The closing `)` should stay on the line of the last one. +- **A binary operator that continues an expression starts the new line**: `=`, `+=`, `&&`, `+`, `|`, `==` and the + others. +- **In a long ternary, `?` and `:` start their lines.** +- **In an expression over several lines, `(` stays on the line of the first operand and `)` on the line of the last.** + Parentheses are added only where they make the meaning clearer. + +```c +Example_List_CopyRange(aInOut_pDestinationList, + aIn_pSourceList, + aFirstIndex, + aCount, + aOut_pCopiedCount); + +bool isWithinLimits = aIn_pList->count + aAdditionalCount <= EXAMPLE_LIST_MAX_VALUES + && aIn_pList->capacity <= SIZE_MAX / sizeof(*aIn_pList->pValues); +``` + +## 2.6 Alignment + +Consecutive lines line up, so a block of declarations reads as a table: + +- the names and the `=` of declarations in one group, and consecutive assignments, compound ones included; +- the member names of a `struct` or `union`, and the `:` of bit-fields; +- the `=` of enumerators; +- the values of consecutive parameterless macros, and the `\` of a macro over several lines. + +```c +typedef struct Example_Header +{ + unsigned int kind : 4; + unsigned int flags : 4; + size_t size; +} Example_tHeader; +``` + +## The profile + +Copy this file to `.clang-format` at the root of the project. It needs `clang-format` 23; pin one exact version in CI, +because two versions can format the same file differently. + +```yaml +--- +Language: Cpp +BasedOnStyle: LLVM + +IndentWidth: 8 +ContinuationIndentWidth: 8 +TabWidth: 8 +UseTab: Never +ColumnLimit: 100 + +BreakAfterReturnType: All +BreakBeforeBraces: Custom +BraceWrapping: + AfterFunction: true + AfterStruct: true + AfterUnion: true + AfterEnum: true + AfterCaseLabel: true + AfterControlStatement: Always + BeforeElse: false + BeforeWhile: false + AfterExternBlock: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + +AllowShortFunctionsOnASingleLine: Empty +AllowShortBlocksOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +SpaceInEmptyBraces: Always + +SpaceBeforeParens: Never +SpacesInParens: Never +SpacesInSquareBrackets: true +SpaceBeforeSquareBrackets: false +SpaceAfterCStyleCast: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +BitFieldColonSpacing: Both +PointerAlignment: Left +DerivePointerAlignment: false + +AlignAfterOpenBracket: true +AlignOperands: DontAlign +BreakBeforeBinaryOperators: All +BreakAfterOpenBracketFunction: false +BreakBeforeCloseBracketFunction: false +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +PackArguments: + BinPack: OnePerLine +PackParameters: + BinPack: OnePerLine +PenaltyBreakAssignment: 100 + +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: true + PadOperators: false + EnumAssignments: true +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignFunctionDeclarations: false +AlignConsecutiveBitFields: Consecutive +AlignConsecutiveMacros: Consecutive +AlignEscapedNewlines: Left + +IndentCaseLabels: false +IndentCaseBlocks: false +IndentGotoLabels: NoIndent +IndentPPDirectives: AfterHash +PPIndentWidth: 4 + +Cpp11BracedListStyle: Block +BracedInitializerIndentWidth: 8 +EnumTrailingComma: Insert + +NumericLiteralCase: + ExponentLetter: Lower + HexDigit: Upper + Prefix: Lower + Suffix: Upper + +SortIncludes: + Enabled: true + IgnoreCase: false +IncludeBlocks: Regroup +IncludeIsMainRegex: '$^' +IncludeCategories: + - Regex: '^<(assert|complex|ctype|errno|fenv|float|inttypes|iso646|limits|locale|math|setjmp|signal|stdalign|stdarg|stdatomic|stdbool|stddef|stdint|stdio|stdlib|stdnoreturn|string|tgmath|threads|time|uchar|wchar|wctype)\.h>$' + Priority: 1 + - Regex: '^<' + Priority: 2 + - Regex: '^"' + Priority: 3 + +MaxEmptyLinesToKeep: 1 +KeepEmptyLines: + AtStartOfBlock: false + AtStartOfFile: false + AtEndOfFile: false +ReflowComments: false +... +``` + +- `PenaltyBreakAssignment: 100` keeps a call on the line of its `=` and puts one argument on each line when the + arguments do not fit; with the LLVM default, the formatter breaks before the `=` first. +- `IncludeIsMainRegex: '$^'` stops the formatter from moving a source file's own header to the top: the groups of + [Files and headers](FILES-AND-HEADERS.md#43-includes) decide the order. +- `EnumTrailingComma: Insert` puts the comma after the last enumerator. LLVM documents that the option can change + code in ways that need review, so a change it makes is reviewed like any other. + +## What the tool leaves to you + +`clang-format` 23 cannot express every rule above. These are checked in review, and the formatter's output is +corrected where it differs: + +- **`return(value)`**: `clang-format` puts a space after `return` whatever the profile says, and writes + `return (value);`. +- **Compound literals**: `SpaceAfterCStyleCast` also puts a space before the `{` of a compound literal, + `(Example_tUserData) { 0 }`. +- **An empty `do` body**: `do`, then `{ } while(condition);` is split into `{` and `} while(condition);`. +- **One statement per body without braces** (2.3), the order of declaration groups and their blank lines, the blank + lines around `case` groups and `goto` labels, and the columns of `@param` lines. + +A part of a file the formatter must not touch may be wrapped in `/* clang-format off */` and `/* clang-format on */`, +as narrowly as the rule needs. diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/LANGUAGE.md b/Progmasoft_Core_C_Coding_Guidelines/C11/LANGUAGE.md new file mode 100644 index 0000000..a2c78e8 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/LANGUAGE.md @@ -0,0 +1,31 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 9. Language + +The guidelines are written for ISO C11: code compiles with `-std=c11 -pedantic-errors`. + +## 9.1 Extensions + +- **No language extensions.** Two constructs that are not ISO C11 are part of every header and are allowed: + `#pragma once`, and `extern "C"` inside `#ifdef __cplusplus`, which a C compiler never sees + ([Files and headers](FILES-AND-HEADERS.md#42-the-start-of-a-header)). +- **`{}` is not C11**: an empty initializer is `{ 0 }`. + +## 9.2 C11 features + +- **`bool`, `true` and `false` come from `<stdbool.h>`** and should be used for every truth value. +- **`restrict` may be used only where the aliasing contract has been checked**; in a public interface, the + documentation states what it forbids the caller. +- **An `_Atomic` variable is named like any other variable.** `_Atomic(Type)` should be preferred to the qualifier form. +- **`_Thread_local` adds no prefix to a name.** +- **`_Alignas`, `_Alignof`, `_Static_assert`, `_Generic` and `_Noreturn` are used where they mean something.** + `_Static_assert` always has a message that says what failed; `_Noreturn` marks only functions that never return. +- **`volatile` does not synchronize threads.** Shared state between threads uses `_Atomic` or the functions of + `<threads.h>` or the platform. +- **`auto` and `register` should not be written.** + +```c +_Static_assert(EXAMPLE_LIST_MAX_VALUES <= SIZE_MAX / sizeof(int), + "EXAMPLE_LIST_MAX_VALUES must fit in a size_t of bytes."); +``` diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/MEMORY-AND-OWNERSHIP.md b/Progmasoft_Core_C_Coding_Guidelines/C11/MEMORY-AND-OWNERSHIP.md new file mode 100644 index 0000000..2881f15 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/MEMORY-AND-OWNERSHIP.md @@ -0,0 +1,102 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 8. Memory and ownership + +None of this is formatting, and no tool checks all of it: review does. + +## 8.1 Ownership + +- **Every dynamic object has a contract**: who owns it, when ownership moves, how long a borrowed pointer stays valid, + and what state a failure leaves behind. The function's documentation states it. +- **The names say it too**: `Create` returns an object the caller owns and `Destroy` frees, `Init` and `Deinit` work on + memory the caller already has ([Naming](NAMING.md#36-what-function-names-mean)). +- **Ordinary allocation failures should be reported to the caller.** `abort` and `exit` may end the program only in a + documented case that cannot be recovered; a library does not end the process of its caller by surprise. +- **A wrapper allocator may be used**; without a need for one, the standard functions are called directly. + +## 8.2 Allocating + +- **`calloc` should be used when every bit must start at zero, and `malloc` otherwise.** All-bits-zero is not the zero + value of every C type, such as a pointer or a floating-point number on every platform. +- **The size should come from the target**: `malloc(sizeof(*pValue))`, not `malloc(sizeof(Type))`, so that the size + follows a change of the pointer's type. +- **The result of `malloc`, `calloc` and `realloc` is not cast.** +- **Nothing allocates zero bytes**: no `malloc(0)`, `calloc(0, size)`, `calloc(count, 0)` or `realloc(pBlock, 0)`. + Their results differ between implementations. A request for zero elements is an empty result or an invalid argument, + as the contract says. +- **A size computation cannot overflow**: a multiplication or an addition is checked against `SIZE_MAX` first. + +## 8.3 Growing and shrinking + +- **`realloc` writes to a temporary pointer, which is checked before it replaces the old one.** On failure the old + block is still valid and still owned; writing the result straight back would lose it. +- **After a successful `realloc`, the old pointer and every pointer into the old block are invalid**, even when the + address did not change. +- **New memory is initialized before it is read**, and not zeroed when it will be written first anyway. +- **A general-purpose dynamic array should grow geometrically.** A failed growth leaves the pointer, the capacity and + the size as they were. +- **Removing elements should only lower the logical size.** Memory is given back when the caller asks; an array that + shrinks by itself does so with hysteresis, so that adding and removing one element does not reallocate each time. + What happens at zero elements is part of the contract. + +```c +bool +Example_List_Append(Example_List_tList* aInOut_pList, int aValue) +{ + if(aInOut_pList == NULL) + return(false); + + if(aInOut_pList->count == aInOut_pList->capacity) + { + size_t newCapacity; + + if(aInOut_pList->capacity == 0U) + newCapacity = 8U; + else + { + if(aInOut_pList->capacity > SIZE_MAX / 2U) + return(false); + + newCapacity = aInOut_pList->capacity * 2U; + } + + if(newCapacity > SIZE_MAX / sizeof(*aInOut_pList->pValues)) + return(false); + + int* pTemporary = realloc(aInOut_pList->pValues, newCapacity * sizeof(*pTemporary)); + + if(pTemporary == NULL) + return(false); + + aInOut_pList->pValues = pTemporary; + aInOut_pList->capacity = newCapacity; + } + + aInOut_pList->pValues[ aInOut_pList->count ] = aValue; + aInOut_pList->count++; + + return(true); +} +``` + +## 8.4 Freeing + +- **`free(NULL)` does nothing, so no check is added only to protect a `free`.** +- **A pointer that stays in scope after its block is freed should be set to `NULL`** when it could be used again. + +```c +void +Example_List_Deinit(Example_List_tList* aInOut_pList) +{ + if(aInOut_pList == NULL) + return; + + free(aInOut_pList->pValues); + aInOut_pList->pValues = NULL; + aInOut_pList->count = 0U; + aInOut_pList->capacity = 0U; +} +``` + +The check of `aInOut_pList` protects the member accesses, not the `free`. diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/NAMING.md b/Progmasoft_Core_C_Coding_Guidelines/C11/NAMING.md new file mode 100644 index 0000000..790e382 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/NAMING.md @@ -0,0 +1,122 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 3. Naming + +A name in C says what kind of thing it is, where it lives and, in a public interface, which module owns it. The +prefixes below carry that; the words after them say what the thing is for. + +## 3.1 Variables + +| Kind | Style | Example | +| --- | --- | --- | +| Local variable, `const` variable | `camelCase` | `userCount`, `maxCount` | +| Global variable | `gPascalCase` | `gMaxCount` | +| `static` variable in a function | `sPascalCase` | `sCallCount` | +| `static` variable at file scope | `gsPascalCase` | `gsCounter` | +| Pointer | `pPascalCase` | `pUser` | +| Pointer to a pointer | `ppPascalCase` | `ppUser` | +| Global pointer | `gpPascalCase` | `gpUser` | +| `static` pointer at file scope | `gspPascalCase` | `gspUser` | +| `static` pointer in a function | `spPascalCase` | `spUser` | + +- **Each level of pointer adds one `p`**: `pItem`, `ppItem`, `pppItem`, and in the same way `gpp`, `gspp`, `spp`. +- **The prefixes come in a fixed order**: the scope (`g`), the storage (`s`), one `p` per pointer + level, then the name in `PascalCase`. +- **`const` and `restrict` add no prefix.** A pointer to a function takes the pointer prefixes like any other pointer. +- **A Boolean says what it states**, with `is`, `did`, `can` or `has` where they fit: `isReady`, `hasError`. The scope + and storage prefixes come first: `gIsReady`, `gsHasError`. + +## 3.2 Global state + +- **A public interface declares no global variable**, not even a `const` one. +- **An internal global that is not `static` must be `const`.** State that changes lives in a `static` variable at file + scope or in an object that the caller passes in. +- **Constants of one file should be `static const`.** A constant that several files of the module share may be + `extern const`. In C, `const` alone does not give a name internal linkage. + +## 3.3 Parameters + +| Kind | Style | Example | +| --- | --- | --- | +| Plain | `aPascalCase` | `aCount` | +| Input | `aIn_PascalCase` | `aIn_Count` | +| Output | `aOut_PascalCase` | `aOut_Result` | +| Input and output | `aInOut_PascalCase` | `aInOut_Buffer` | +| Input pointer | `aIn_pPascalCase` | `aIn_pData` | +| Output pointer to a pointer | `aOut_ppPascalCase` | `aOut_ppData` | +| Input and output, three pointer levels | `aInOut_pppPascalCase` | `aInOut_pppData` | + +- **The direction comes before the pointer level**: `aOut_pResult`, never `apOut_Result`. +- **Only a plain scalar parameter may go without a direction**: `aCount`, `aValue`. +- **The direction in the name matches the direction in the documentation**: `aOut_pResult` is `@param[out]`. + +## 3.4 Functions, types, constants and macros + +- **Functions are `PascalCase`**, `static` and `static inline` ones too, with no prefix for either. +- **The tags of `struct`, `union` and `enum` are `PascalCase`.** +- **A `typedef` is `tPascalCase`**; a `typedef` of a function pointer is `tFn_PascalCase`. +- **Enumerators are `kPascalCase`.** +- **Macros are `UPPER_SNAKE_CASE`**, and the parameters of a function-like macro are `dA_PascalCase`. + +## 3.5 Modules + +**Every type, function and macro of a public interface carries the module's prefix**, the parts of the module name +joined by underscores. For a public enumerator, the module prefix comes before the `k`: + +```c +typedef struct Example_List_List +{ + size_t count; +} Example_List_tList; + +typedef enum Example_List_Status +{ + Example_List_kSuccess, + Example_List_kFailure, +} Example_List_tStatus; + +typedef void (*Example_List_tFn_Visit)(int aValue); + +#define EXAMPLE_LIST_MAX_VALUES 1024U + +Example_List_tList* +Example_List_Create(void); +``` + +- **Every macro carries the module prefix**, internal macros as well as public ones. +- **An internal enumerator should be plain `kPascalCase`**: `kReady`. It may take the module prefix where the short name + could collide. +- **An internal function needs no module prefix.** + +A module's name also names its files ([Files and headers](FILES-AND-HEADERS.md#41-file-and-directory-names)). + +## 3.6 What function names mean + +A verb at the start of a function name promises a behavior. A function keeps the promise of the verb it uses: + +| Name | Meaning | +| --- | --- | +| `Create` / `Destroy` | Allocate an object the caller then owns / release it, memory included. | +| `Init` / `Deinit` | Set up an object whose memory already exists / release what it holds, but not its own memory. | +| `Open` / `Close` | Acquire a resource / release it; `Close` does not free the object's own memory. | +| `Is` | Ask a Boolean property; changes nothing. | +| `Did` | Ask whether an event happened or finished; changes nothing. | +| `Can` | Ask whether an operation is possible, without doing it. | +| `Has` | Ask about ownership, presence, containment or a feature; changes nothing. | +| `Set` | Change a value or a property. | +| `Try` | An operation for which failing is an ordinary outcome. Not every function that can fail needs it. | +| `Find` | Search; finding nothing is an ordinary outcome. | +| `Remove` | Take out of a collection or a relation. | +| `Delete` | Remove a lasting resource: a file, a record. | +| `Add` / `Insert` / `Append` | Add / put at a given position / put at the end. | +| `Clear` / `Reset` | Empty the contents / go back to the defined default state. | +| `Copy` / `Clone` / `Move` | Copy into an existing target / make an independent object / hand over ownership. | +| `Compare` / `Equals` | Order, as the sign of an `int` / equality, as a `bool`. | +| `Validate` / `Check` | Check against rules / check a condition or a state. | +| `Parse` / `Convert` | Read a syntax / change a representation or a type. | +| `Read` / `Write` | Move data from a source / to a target. | + +- **A getter needs no `Get`**: it may be named for the property, `BufferSize()`. +- **A setter starts with `Set`.** +- **The contract of a function states who owns what, and what happens when it fails**; the name only announces it. diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/PREPROCESSOR.md b/Progmasoft_Core_C_Coding_Guidelines/C11/PREPROCESSOR.md new file mode 100644 index 0000000..9ad744a --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/PREPROCESSOR.md @@ -0,0 +1,45 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 7. Preprocessor + +## 7.1 Conditions + +- **`#ifdef` and `#ifndef` should be used only to ask whether a name is defined.** A combined or numeric condition may + use `#if`. +- **The whole condition of `#if` and `#elif` is in parentheses**: `#if (EXAMPLE_LIST_LEVEL > 1)`. +- **Nested directives keep `#` in the first column and indent after it by four spaces per level.** + +```c +#if (EXAMPLE_LIST_LEVEL > 1) +# if defined(EXAMPLE_LIST_TRACE) +# define EXAMPLE_LIST_LOG_LEVEL 2U +# endif +#endif +``` + +## 7.2 Macros + +- **The values of consecutive parameterless macros line up.** +- **The `\` of a macro over several lines stand in one column**, and nothing follows a `\`, not even a space. +- **`#` is separated from its parameter by one space, and `##` has one space on each side**: `# dA_Value`, + `dA_First ## dA_Second`. +- **A macro of several statements uses `do`, `{` on its own line, and `} while(0)`**, so that it is one statement where + it is used. An operation that is an ordinary function should be a `static inline` function instead. +- **A macro evaluates each parameter at most once at run time.** `EXAMPLE_MAX(a, b)` that evaluates the larger one + twice runs a side effect twice. +- **Each use of a parameter is parenthesized where precedence could change its meaning.** + +```c +#define EXAMPLE_LIST_MAX_VALUES 1024U +#define EXAMPLE_LIST_MIN_VALUES 16U + +#define EXAMPLE_LIST_RESET(dA_Value) \ + do \ + { \ + (dA_Value) = 0; \ + } while(0) +``` + +[Naming](NAMING.md#34-functions-types-constants-and-macros) gives the names of macros and their parameters; every macro +carries the module prefix ([Modules](NAMING.md#35-modules)). diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/PRINCIPLES.md b/Progmasoft_Core_C_Coding_Guidelines/C11/PRINCIPLES.md new file mode 100644 index 0000000..24a7b49 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/PRINCIPLES.md @@ -0,0 +1,42 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 1. Principles + +Progmasoft Core C Coding Guidelines are for projects written in C. They are a style of their own, not the C subset of +[Progmasoft Core C++ Coding Guidelines](../../Progmasoft_Core_Cpp_Coding_Guidelines/Common/PRINCIPLES.md): names, +layout and comments differ on purpose. A C interface that a C++ library exposes follows the C++ guidelines +([C interfaces](../../Progmasoft_Core_Cpp_Coding_Guidelines/Common/C-INTERFACES.md)). + +## 1.1 The language and the tools + +- **The language is ISO C11.** What C11 offers and how it is used is in [Language](LANGUAGE.md). +- **The toolchain is LLVM 23**: Clang compiles, and `clang-format` and `clang-tidy` 23 run the profiles in + [Formatting](FORMATTING.md#the-profile) and [Tooling](TOOLING.md#111-the-clang-tidy-profile). +- **No language extensions**, with two exceptions that every header uses: `#pragma once`, and the conditional + `extern "C"` block of a public header ([Files and headers](FILES-AND-HEADERS.md)). + +## 1.2 How the rules are written + +Each rule says what to do. **Must** is a rule a review enforces, and **must not** forbids; an exception exists only +where the rule names one. **Should** is the default, which a technical reason, written next to the code, may override. +**May** leaves the choice to the author. + +## 1.3 Names carry the kind of a thing + +A C program has one namespace and no types that a tool shows on hover in every reader's editor. So a name says what it +is: its prefixes give the scope, the storage and the pointer depth (`gspUser`), the direction of a parameter +(`aOut_pResult`) and the module it belongs to (`Example_List_Create`). A reader knows from the name alone whether a +line changes a global, writes through an out parameter or calls into another module. + +## 1.4 Ownership is a contract + +C has no destructors. Every function that allocates, frees, borrows or hands over memory says so, in its name +([Naming](NAMING.md#36-what-function-names-mean)) and in its documentation, and leaves a defined state behind when it +fails ([Memory and ownership](MEMORY-AND-OWNERSHIP.md)). + +## 1.5 Tools do what they can; review does the rest + +`clang-format` lays out the code, `clang-tidy` and the compiler catch a set of bugs. Neither checks the naming scheme, +ownership, Doxygen content or every initializer rule. [Tooling](TOOLING.md#113-what-review-checks) lists what review +covers, and where the formatter and the guidelines disagree, the guidelines are the rule. diff --git a/Progmasoft_Core_C_Coding_Guidelines/C11/TOOLING.md b/Progmasoft_Core_C_Coding_Guidelines/C11/TOOLING.md new file mode 100644 index 0000000..2f24577 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/TOOLING.md @@ -0,0 +1,67 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 11. Tooling + +The toolchain is LLVM 23. The names of the binaries differ between distributions, `clang-format-23` or +`clang-format`, so check the version before relying on a result. + +## 11.1 The clang-tidy profile + +Copy this file to `.clang-tidy` at the root of the project. It is deliberately narrow: checks that apply to C and find +real bugs. It does not check the naming scheme, ownership or Doxygen content, and it does not replace the compiler or +review. + +```yaml +--- +Checks: >- + -*, + clang-analyzer-core.*, + clang-analyzer-deadcode.*, + clang-analyzer-unix.Malloc, + bugprone-macro-repeated-side-effects, + bugprone-sizeof-expression, + bugprone-suspicious-memset-usage +WarningsAsErrors: '' +HeaderFilterRegex: '.*' +FormatStyle: file +SystemHeaders: false +... +``` + +`bugprone-macro-repeated-side-effects` catches a macro that evaluates a parameter twice +([Preprocessor](PREPROCESSOR.md#72-macros)), `bugprone-sizeof-expression` a `sizeof` of the wrong thing in an +allocation. A project that adds checks chooses them for C: groups such as `modernize-*` are written for C++ and report +false positives on C code. Run `clang-tidy` with the real compiler arguments, preferably from `compile_commands.json`. + +## 11.2 Commands + +```sh +clang-format --version +clang-format --style=file --dry-run --Werror Example.List.c Example.List.h +clang-tidy --version +clang-tidy Example.List.c -- -std=c11 -I. +clang -std=c11 -pedantic-errors -Wall -Wextra -I. -fsyntax-only Example.List.c +``` + +`clang-format --dry-run --Werror` reports the places where the formatter's output differs from the file, including the +few where the guidelines are right and the formatter is not ([Formatting](FORMATTING.md#what-the-tool-leaves-to-you)). + +## 11.3 What review checks + +- A comma after the last item of an initializer over several lines, and none in a list on one line. +- Doxygen: `@brief`, the direction of each parameter, documentation at both the declaration and the definition, the + order of the parts. +- A valid value before the first read; each macro parameter evaluated once. +- `realloc` through a temporary pointer, no allocation of zero bytes, overflow checks on sizes, ownership. +- Module prefixes of public names, include paths, and file and directory names that match the module. +- The line breaks the formatter cannot make, the blank lines around `goto` labels, and the forms in + [What the tool leaves to you](FORMATTING.md#what-the-tool-leaves-to-you). + +## 11.4 References + +- [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174): the + meaning of must, should and may. +- [Clang-Format Style Options](https://releases.llvm.org/23.1.0/tools/clang/docs/ClangFormatStyleOptions.html), 23.1.0. +- [Clang-Tidy](https://releases.llvm.org/23.1.0/tools/clang/tools/extra/docs/clang-tidy/index.html) and [its + checks](https://releases.llvm.org/23.1.0/tools/clang/tools/extra/docs/clang-tidy/checks/list.html), 23.1.0. diff --git a/Progmasoft_Core_C_Coding_Guidelines/index.json b/Progmasoft_Core_C_Coding_Guidelines/index.json new file mode 100644 index 0000000..0587fb0 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/index.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://schemastore.progmasoft.com/json/progmasoft-cpp-index.json", + "title": "Progmasoft Core C Coding Guidelines", + "license": "CC-BY-4.0", + "standards": [ + { + "id": "c11", + "name": "C11", + "default": true, + "for": "every C project", + "documents": [ + "C11/PRINCIPLES.md", + "C11/FORMATTING.md", + "C11/NAMING.md", + "C11/FILES-AND-HEADERS.md", + "C11/CONTROL-FLOW.md", + "C11/DECLARATIONS-AND-INITIALIZERS.md", + "C11/PREPROCESSOR.md", + "C11/MEMORY-AND-OWNERSHIP.md", + "C11/LANGUAGE.md", + "C11/COMMENTS-AND-DOCUMENTATION.md", + "C11/TOOLING.md" + ] + } + ], + "documents": [ + { "id": "principles", "chapter": 1, "title": "Principles", "path": "C11/PRINCIPLES.md", "standards": ["c11"] }, + { "id": "formatting", "chapter": 2, "title": "Formatting", "path": "C11/FORMATTING.md", "standards": ["c11"] }, + { "id": "naming", "chapter": 3, "title": "Naming", "path": "C11/NAMING.md", "standards": ["c11"] }, + { "id": "files-and-headers", "chapter": 4, "title": "Files and headers", "path": "C11/FILES-AND-HEADERS.md", "standards": ["c11"] }, + { "id": "control-flow", "chapter": 5, "title": "Control flow", "path": "C11/CONTROL-FLOW.md", "standards": ["c11"] }, + { "id": "declarations-and-initializers", "chapter": 6, "title": "Declarations and initializers", "path": "C11/DECLARATIONS-AND-INITIALIZERS.md", "standards": ["c11"] }, + { "id": "preprocessor", "chapter": 7, "title": "Preprocessor", "path": "C11/PREPROCESSOR.md", "standards": ["c11"] }, + { "id": "memory-and-ownership", "chapter": 8, "title": "Memory and ownership", "path": "C11/MEMORY-AND-OWNERSHIP.md", "standards": ["c11"] }, + { "id": "language", "chapter": 9, "title": "Language", "path": "C11/LANGUAGE.md", "standards": ["c11"] }, + { "id": "comments-and-documentation", "chapter": 10, "title": "Comments and documentation", "path": "C11/COMMENTS-AND-DOCUMENTATION.md", "standards": ["c11"] }, + { "id": "tooling", "chapter": 11, "title": "Tooling", "path": "C11/TOOLING.md", "standards": ["c11"] } + ] +} diff --git a/README.md b/README.md index 437e9dd..b7906d3 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ conventions each time. | Guidelines | Languages | State | | --- | --- | --- | | [Progmasoft Core C++ Coding Guidelines](#progmasoft-core-c-coding-guidelines) | C++17, C++20 | written | -| `Progmasoft_Core_C_Coding_Guidelines/` | C11 | not written yet | +| [Progmasoft Core C Coding Guidelines](#progmasoft-core-c-coding-guidelines) | C11 | written | | `Progmasoft_Chene_Cpp_Coding_Guidelines/` | C++20 | not written yet | They are written for anyone who wants a complete, opinionated rule set to adopt. Progmasoft's own C++ projects follow @@ -80,6 +80,44 @@ records a deviation. [Contributing](CONTRIBUTING.md) explains how to propose a c - Tests sit next to the code they test; sanitizers and fuzzers run in CI. The guidelines prescribe no test, fuzzing or benchmark framework, and no error library: it prescribes how they are used. +## Progmasoft Core C Coding Guidelines + +The guidelines for C11, in `Progmasoft_Core_C_Coding_Guidelines/`. They are a style of their own, not the C part of the +C++ guidelines: a C interface of a C++ library follows the C++ guidelines, a C project follows these. + +### Contents + +| Chapter | Covers | +| --- | --- | +| [1. Principles](Progmasoft_Core_C_Coding_Guidelines/C11/PRINCIPLES.md) | C11 and LLVM 23, how the rules are worded, what tools check and what review checks | +| [2. Formatting](Progmasoft_Core_C_Coding_Guidelines/C11/FORMATTING.md) | the `.clang-format` profile, and the forms it cannot produce | +| [3. Naming](Progmasoft_Core_C_Coding_Guidelines/C11/NAMING.md) | prefixes for scope, storage, pointers and parameters; modules; what function names mean | +| [4. Files and headers](Progmasoft_Core_C_Coding_Guidelines/C11/FILES-AND-HEADERS.md) | file and directory names, `#pragma once`, `extern "C"`, includes | +| [5. Control flow](Progmasoft_Core_C_Coding_Guidelines/C11/CONTROL-FLOW.md) | conditions, `return`, loops, `switch`, `goto` | +| [6. Declarations and initializers](Progmasoft_Core_C_Coding_Guidelines/C11/DECLARATIONS-AND-INITIALIZERS.md) | declarations, `typedef`, literals, initializers | +| [7. Preprocessor](Progmasoft_Core_C_Coding_Guidelines/C11/PREPROCESSOR.md) | conditions and macros | +| [8. Memory and ownership](Progmasoft_Core_C_Coding_Guidelines/C11/MEMORY-AND-OWNERSHIP.md) | ownership contracts, `malloc` and `realloc`, growing and freeing | +| [9. Language](Progmasoft_Core_C_Coding_Guidelines/C11/LANGUAGE.md) | extensions, `bool`, `restrict`, `_Atomic`, `_Static_assert` and the other C11 features | +| [10. Comments and documentation](Progmasoft_Core_C_Coding_Guidelines/C11/COMMENTS-AND-DOCUMENTATION.md) | comments, Doxygen and the order of its parts | +| [11. Tooling](Progmasoft_Core_C_Coding_Guidelines/C11/TOOLING.md) | the `.clang-tidy` profile, commands, what review checks | + +With one version, the chapters are all in `C11/`. [`index.json`](Progmasoft_Core_C_Coding_Guidelines/index.json) lists +them in the same form as the C++ index. + +### The short version + +- ISO C11 with `-pedantic-errors`, no extensions but `#pragma once` and `extern "C"`; Clang, `clang-format` and + `clang-tidy` 23. +- Eight spaces, 100 columns, the return type on its own line, braces on their own line, and no braces around a body of + one statement. `if(`, `return(value);`, `int* pValue`, `values[ index ]`. +- `camelCase` locals with `g`, `s` and one `p` per pointer level as prefixes (`gspUser`); parameters `aCount`, + `aIn_pData`, `aOut_pResult`; functions and tags `PascalCase`; `typedef` `tPascalCase`; enumerators `kPascalCase`; + macros `UPPER_SNAKE_CASE`; public names prefixed by their module, `Example_List_Create`. +- Files named after their module, `example/Example.List.h`. +- Ownership in names and contracts: `Create` and `Destroy`, `Init` and `Deinit`; `realloc` through a temporary pointer; + no allocation of zero bytes; sizes checked for overflow. +- Every function documented with Doxygen, at its declaration and its definition. + ## License The text is licensed under [CC BY 4.0](LICENSE.md). The configuration files and code examples are dedicated to the