|
| 1 | +/** |
| 2 | + * @id c/misra/definitions-in-header |
| 3 | + * @name RULE-8-18: There shall be no tentative definitions in a header file |
| 4 | + * @description Tentative definitions in headers can introduce unintended definitions in multiple |
| 5 | + * translation units. |
| 6 | + * @kind problem |
| 7 | + * @precision high |
| 8 | + * @problem.severity warning |
| 9 | + * @tags external/misra/id/rule-8-18 |
| 10 | + * correctness |
| 11 | + * external/misra/c/2025 |
| 12 | + * external/misra/obligation/required |
| 13 | + */ |
| 14 | + |
| 15 | +import cpp |
| 16 | +import codingstandards.c.misra |
| 17 | + |
| 18 | +/** |
| 19 | + * An initialized definition of a variable, for example: |
| 20 | + * ```c |
| 21 | + * int global_object = 1; |
| 22 | + * ``` |
| 23 | + */ |
| 24 | +class InitializedDefinition extends VariableDeclarationEntry { |
| 25 | + InitializedDefinition() { |
| 26 | + exists(Initializer initializer | |
| 27 | + this.isDefinition() and |
| 28 | + initializer = this.getVariable().getInitializer() and |
| 29 | + ( |
| 30 | + initializer.getLocation().subsumes(this.getLocation()) |
| 31 | + or |
| 32 | + // Initializers follow their own declarators, not definitions in other translation units. |
| 33 | + this.getLocation().isBefore(initializer.getLocation(), _) and |
| 34 | + not exists(VariableDeclarationEntry later | |
| 35 | + later.getVariable() = this.getVariable() and |
| 36 | + later.isDefinition() and |
| 37 | + this.getLocation().isBefore(later.getLocation(), _) and |
| 38 | + ( |
| 39 | + later.getLocation().isBefore(initializer.getLocation(), _) or |
| 40 | + initializer.getLocation().subsumes(later.getLocation()) |
| 41 | + ) |
| 42 | + ) |
| 43 | + ) |
| 44 | + ) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * A tentative definition of a file-scope variable, for example: |
| 50 | + * ```c |
| 51 | + * int global_object; |
| 52 | + * static int internal_object; |
| 53 | + * ``` |
| 54 | + */ |
| 55 | +class TentativeDefinition extends VariableDeclarationEntry { |
| 56 | + TentativeDefinition() { |
| 57 | + this.getVariable() instanceof GlobalVariable and |
| 58 | + not this.hasSpecifier("extern") and |
| 59 | + not this instanceof InitializedDefinition |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +from TentativeDefinition definition |
| 64 | +where |
| 65 | + not isExcluded(definition, Declarations5Package::definitionsInHeaderQuery()) and |
| 66 | + exists(Include include | include.getIncludedFile() = definition.getFile()) |
| 67 | +select definition, |
| 68 | + "Tentative definition of '" + definition.getName() + "' appears in a header file." |
0 commit comments