diff options
| author | Leitwolf | 2026-11-15 19:31:36 +0300 |
|---|---|---|
| committer | GitHub | 2026-11-15 19:31:36 +0300 |
| commit | d2b1a1ffc6c7379d0c882d6f3d11a7466ec57c5a (patch) | |
| tree | ec518d93ac2115c96f0b61b3fc0211cb0e37bd35 | |
| parent | f57d68b8ec3da1f79d7eca6b9eb7679254fcc2f9 (diff) | |
| parent | 1baf19e8ed000f645028318bec247fb0d5c66936 (diff) | |
| download | progmasoft-cpp-d2b1a1ffc6c7379d0c882d6f3d11a7466ec57c5a.tar.gz | |
Merge pull request #5 from Progmasoft/docs/core-c-guidelines
Write Progmasoft Core C Coding Guidelines
18 files changed, 1025 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. @@ -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 --- a/Progmasoft_Core_C_Coding_Guidelines/.gitkeep +++ /dev/null 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 --- a/Progmasoft_Core_C_Coding_Guidelines/C11/.gitkeep +++ /dev/null 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..c6cf685 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/COMMENTS-AND-DOCUMENTATION.md @@ -0,0 +1,63 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <[email protected]> --> +<!-- 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 a +line that holds only the `*` of the comment. + +```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..090f066 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/CONTROL-FLOW.md @@ -0,0 +1,77 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <[email protected]> --> +<!-- 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 <[email protected]> --> +<!-- 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 <[email protected]> --> +<!-- 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..5c4dd22 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/FORMATTING.md @@ -0,0 +1,249 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <[email protected]> --> +<!-- 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, after one space**: `return (result);`, the form + `clang-format` writes. 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: + +- **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 <[email protected]> --> +<!-- 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..5dc7199 --- /dev/null +++ b/Progmasoft_Core_C_Coding_Guidelines/C11/MEMORY-AND-OWNERSHIP.md @@ -0,0 +1,102 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <[email protected]> --> +<!-- 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 <[email protected]> --> +<!-- 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 |