Projet

Général

Profil

Wiki » Historique » Version 104

Patrice Nadeau, 2023-12-31 12:08

1 1 Patrice Nadeau
# Règles de codage C
2
3 68 Patrice Nadeau
Le langage C, version [C99] (https://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf) utilisé avec le compilateur [GCC](https://gcc.gnu.org/).
4 1 Patrice Nadeau
> `gcc` n'est pas entièrement compatible avec le standard C99 (<https://gcc.gnu.org/c99status.html>).
5
6
---
7 73 Patrice Nadeau
8
{{>toc}}
9 1 Patrice Nadeau
10
## Style
11
12 6 Patrice Nadeau
Le code DOIT :
13 5 Patrice Nadeau
* Être dans le style [K&R](https://fr.wikipedia.org/wiki/Style_d%27indentation#Style_K&R) avec la variante *one true brace style* (1TBS):
14 1 Patrice Nadeau
* L’indentation est de 4 espaces
15
* Le « backslash » est utilisé pour les lignes de plus de 80 caractères
16
* Une instruction par ligne
17
* Une espace avant et après un opérateur sauf pour les opérateurs « [unaires](https://fr.wikipedia.org/wiki/Op%C3%A9ration_unaire) »
18 52 Patrice Nadeau
* Les commentaires DOIVENT 
19
    * Être de style C (/* ... */) 
20 50 Patrice Nadeau
    * En minuscules et commencer par une majuscule
21 52 Patrice Nadeau
    * En français
22 50 Patrice Nadeau
    * Précéder l’élément à documenté
23 1 Patrice Nadeau
24 46 Patrice Nadeau
Justifications : 
25 1 Patrice Nadeau
* [K&R](https://fr.wikipedia.org/wiki/Style_d%27indentation#Style_K&R)
26
* Prévient les erreurs lors d'ajout dans les boucles n'ayant qu'une instruction comme bloc
27 46 Patrice Nadeau
* Support ASCII 7-bits
28
* Correspondance avec la fiche technique (datasheet)
29 1 Patrice Nadeau
* [Loi sur la langue officielle et commune du Québec, le français](https://www.publicationsduquebec.gouv.qc.ca/fileadmin/Fichiers_client/lois_et_reglements/LoisAnnuelles/fr/2022/2022C14F.PDF)
30
31
Exemple :
32
``` c
33 47 Patrice Nadeau
int fonction(void) {
34 1 Patrice Nadeau
    int x;
35
    if (var != 1) {
36
        x = x + 1;
37 14 Patrice Nadeau
        y++;
38 91 Patrice Nadeau
        /* Longue ligne */
39 1 Patrice Nadeau
        printf("This is a long\
40
        line that should be splitted");
41
    } else {
42 16 Patrice Nadeau
        x--;
43
    };
44 20 Patrice Nadeau
    return 0;
45
}
46
```
47
48 93 Patrice Nadeau
## Commentaires Doxygen
49 99 Patrice Nadeau
La documentation est faite a l'aide de commentaires [Doxygen](https://www.doxygen.nl/) dans la déclaration de tous les objets ayant une visibilité publique ainsi que pour les macros.
50 96 Patrice Nadeau
* Dans le format *Javadoc* (`/** */`)
51
* Au minimum, les items suivants doivent être présents :
52 94 Patrice Nadeau
    * `@brief`
53 101 Patrice Nadeau
* Facultatifs
54
    * `@sa` : *See also*
55
    * `@todo`
56 96 Patrice Nadeau
* Les « décorations » (gras, italique, etc.) sont faites avec la syntaxe *Markdown*
57 103 Patrice Nadeau
    * Italique : `*` ou `_`
58
    * Gras : `**` ou `__`
59 96 Patrice Nadeau
* La gradations des notes et remarques se fait selon :
60 95 Patrice Nadeau
   * `@remark` :  Non importante
61 100 Patrice Nadeau
   * `@note` :  Général
62 95 Patrice Nadeau
   * `@attention` : Important
63
   * `@warning` : Conséquence négative
64 90 Patrice Nadeau
    
65
Exemple :
66
``` c
67
/**
68 97 Patrice Nadeau
 * @brief Compteur global
69 1 Patrice Nadeau
 * @warning Note conséquence négative
70 96 Patrice Nadeau
 */
71 97 Patrice Nadeau
int ctr;
72 90 Patrice Nadeau
```
73
74 1 Patrice Nadeau
## Fichiers
75
Le nom des fichiers DOIT être composé de la manière suivante :
76
* En minuscule
77 79 Patrice Nadeau
* Un préfixe de 8 caractères maximum
78
* Un des suffixe (extensions) suivants : 
79
    * `.h` : entête
80
    * `.c` : sources
81
* Contient une section Doxygen :
82
    * `@file`
83
    * `@brief`
84
    * `@version`
85
    * `@date`
86
    * `@author`
87
    * `@copyright`
88 1 Patrice Nadeau
* Les fichier d’entête contiennent en plus
89
    * Une section Doxygen « mainpage » 
90 79 Patrice Nadeau
    * Une définition macro pour éviter de ré-inclure le fichier.
91 1 Patrice Nadeau
92 98 Patrice Nadeau
### Sources
93 104 Patrice Nadeau
Exemple :
94
```c
95
#ifndef _test_h
96
#define _test_h
97
/**
98
 * @file : test.h
99
 * @brief Description
100
 * @version 0.00.01
101
 * @date 2023-02-26
102
 * @author Patrice Nadeau  <pnadeau@patricenadeau.com>
103
 * @copyright 2023 Patrice Nadeau
104
*/
105
...
106
107
#endif /*_usart.h*/
108
```
109 98 Patrice Nadeau
### Entêtes
110 104 Patrice Nadeau
Exemple :
111
```c
112
#ifndef _test_h
113
#define _test_h
114
/**
115
 * @file : test.h
116
 * @brief Description
117
 * @version 0.00.01
118
 * @date 2023-02-26
119
 * @author Patrice Nadeau  <pnadeau@patricenadeau.com>
120
 * @copyright 2023 Patrice Nadeau
121
*/
122
123
/**
124
 * @mainpage lcd
125
 * @brief ATMEL AVR 8-bit C librairie
126
 * @author Patrice Nadeau <pnadeau@patricenadeau.com>
127
 * @version 0.0.02
128
 * @date 2023-03-27
129
 * @pre AVR supportés (testés en gras) :
130
 * - ATmega88
131
 * - ATmega168
132
 * - **ATmega328P**
133
 * @copyright 
134
 * @include{doc} LICENSE.txt
135
*/
136
137
...
138
139
#endif /*_usart.h*/
140
```
141 98 Patrice Nadeau
### Autres
142
143 1 Patrice Nadeau
Exemple :
144
```c
145
#ifndef _test_h
146
#define _test_h
147
/**
148
 * @file : test.h
149
 * @brief Description
150
 * @version 0.00.01
151
 * @date 2023-02-26
152
 * @author Patrice Nadeau  <pnadeau@patricenadeau.com>
153
 * @copyright 2023 Patrice Nadeau
154
*/
155
156
/**
157
 * @mainpage lcd
158 37 Patrice Nadeau
 * @brief ATMEL AVR 8-bit C librairie
159 1 Patrice Nadeau
 * @author Patrice Nadeau <pnadeau@patricenadeau.com>
160
 * @version 0.0.02
161
 * @date 2023-03-27
162 54 Patrice Nadeau
 * @pre AVR supportés (testés en gras) :
163 1 Patrice Nadeau
 * - ATmega88
164
 * - ATmega168
165 15 Patrice Nadeau
 * - **ATmega328P**
166 1 Patrice Nadeau
 * @copyright 
167 13 Patrice Nadeau
 * @include{doc} LICENSE.txt
168 1 Patrice Nadeau
*/
169
170
...
171
172
#endif /*_usart.h*/
173
```
174
175 85 Patrice Nadeau
---
176 82 Patrice Nadeau
177 60 Patrice Nadeau
## Objets
178 1 Patrice Nadeau
179 31 Patrice Nadeau
* Comporter au maximum **31** caractères
180
* Être séparées par des traits de soulignement si comporte plusieurs mots
181
* Exceptions :
182
    * Fonction et variables DOIVENT
183
        * Être en minuscule
184
    * Macros, constantes et `#define` DOIVENT
185
        * Être en majuscule
186 1 Patrice Nadeau
187
Justification :
188
* Linux kernel coding style : <https://www.kernel.org/doc/html/v4.10/process/coding-style.html#naming>
189
* GNU Coding Standards <https://www.gnu.org/prep/standards/html_node/Writing-C.html#Writing-C>
190
* Embedded C Coding Standard : <https://barrgroup.com/embedded-systems/books/embedded-c-coding-standard>
191
192 61 Patrice Nadeau
### Déclarations locales
193 1 Patrice Nadeau
194
Une déclaration n’ayant qu’une visibilité locale DOIT :
195
* Être de classe `static`
196
197
Exemple:
198
``` c
199
/**
200 75 Patrice Nadeau
 * @brief Fonction locale
201
 * @return Une valeur
202
 */
203 7 Patrice Nadeau
static int local_func(void) {
204 1 Patrice Nadeau
    ...
205
    return 0;
206
}
207
```
208
209 62 Patrice Nadeau
### Constantes
210 1 Patrice Nadeau
211
Utilisé au lieu d’une macro quand le type ou la visibilité de la variable doit être définis.
212
213
Exemple :
214
215
``` c
216
/** 
217 38 Patrice Nadeau
 * @name Liste des constantes
218 1 Patrice Nadeau
 * @brief
219
 */
220
/** @{ */
221 38 Patrice Nadeau
/** @brief La chaîne d'initialisation du projet */
222 1 Patrice Nadeau
static const char INIT_STR[6] = "POWER";
223 38 Patrice Nadeau
/** @brief Constante globale de la librairie `random` */
224 1 Patrice Nadeau
extern int RANDOM_MAX = 25;
225
/** @} */
226
227 38 Patrice Nadeau
/** @brief Constante */
228 1 Patrice Nadeau
const int ANSWER 42;
229
```
230
231 63 Patrice Nadeau
### Énumérations
232 1 Patrice Nadeau
233
DOIT être utilisée pour définir une série de valeurs.
234
235
Exemple :
236
```c
237
/**
238 76 Patrice Nadeau
 * @name Liste des valeurs STATUS
239 1 Patrice Nadeau
 * @brief 
240
 * */
241
enum STATUS {
242 76 Patrice Nadeau
	/** @brief Le processus est OK */
243 1 Patrice Nadeau
	STATUS_OK = 0,
244 76 Patrice Nadeau
	/** @brief Le processus est en cours d'initialisation */
245 1 Patrice Nadeau
	STATUS_INIT,
246 76 Patrice Nadeau
	/** @brief Le processus est arrêté */
247 1 Patrice Nadeau
	STATUS_HALTED
248
};
249
```
250
251 64 Patrice Nadeau
### Typedef
252 1 Patrice Nadeau
253
Format :
254
* En minuscule, suivie de **_t**
255
256
Exemple :
257
``` c
258 39 Patrice Nadeau
/** Type de la structure dans la librairie `ds1305` */
259 1 Patrice Nadeau
typedef struct {
260 39 Patrice Nadeau
    /** @brief Dernier deux chiffres : &ge; 00, &le; 99 */
261 1 Patrice Nadeau
    uint8_t year;
262
    /** @brief 01 - 12 */
263
    uint8_t month;
264
    /** @brief 01 - 31 */
265
    uint8_t date;
266
    /** @brief 1 - 7 */
267
    uint8_t day;
268
    /** @brief 00 - 23 */
269
    uint8_t hours;
270
    /** @brief 00 - 59 */
271
    uint8_t minutes;
272
    /** @brief 00 - 59 */
273
    uint8_t seconds;
274
} ds1305_time_t;
275
```
276
277 65 Patrice Nadeau
### Variables
278 1 Patrice Nadeau
279
Exemple :
280
``` c
281 40 Patrice Nadeau
/** @brief Variable locale */
282 1 Patrice Nadeau
static int ctr;
283 40 Patrice Nadeau
/** @brief Variable globale */
284
int RANDOM_CTR;
285 1 Patrice Nadeau
```
286
287 66 Patrice Nadeau
### Structures
288 1 Patrice Nadeau
289
Format
290
* En minuscule, séparé par des «underscores» si nécessaire.
291
292
Exemple :
293
``` c
294
/**
295 76 Patrice Nadeau
* @brief Structure d'un menu local
296 1 Patrice Nadeau
* @see MenuSelect
297
*/
298
struct menu {
299 76 Patrice Nadeau
    /** @brief Caractère utilisé pour l'item */
300 8 Patrice Nadeau
    char choice;
301 76 Patrice Nadeau
    /** @brief Description de l'item */
302 8 Patrice Nadeau
    char *item;
303 1 Patrice Nadeau
};
304
```
305
306 67 Patrice Nadeau
### Fonctions
307 1 Patrice Nadeau
308
Le nom DOIT être dans le format suivant : *Action***_***Item***_***Attribut*, où *Action* signifie :
309 29 Patrice Nadeau
* **set**, **get**, **clear** : Règle, obtient ou vide un registre
310 1 Patrice Nadeau
* **read**, **write** : Lis ou écris dans un fichier
311
* **init** : Fonction d’initialisation
312
* **is** : Vérifie un état
313 36 Patrice Nadeau
* **setup** : Fonction de configuration des ports (AVR)
314 1 Patrice Nadeau
315
Exceptions
316 41 Patrice Nadeau
* Les fonctions définies dans une librairie de bas niveau pour du matériel (« driver ») devraient utiliser le nom définis dans la fiche technique.
317 1 Patrice Nadeau
318
Une fonction DEVRAIT retourner une valeur. 
319 28 Patrice Nadeau
* Type entier (oui/non) :
320 1 Patrice Nadeau
  * Succès : **0**
321
  * Erreur : **1**
322
* Type booléen (Librairie `<stdbool.h>`)
323
    * **true**
324
    * **false**
325
* Pointeur :
326
    * **NULL** : Erreur
327
    * Autre valeur  : adresse du pointeur
328
329
Justification :
330
* [AVR1000b](https://ww1.microchip.com/downloads/en/Appnotes/AVR1000b-Getting-Started-Writing-C-Code-for-AVR-DS90003262B.pdf)
331
332
Exemple :
333
334
``` c
335
/**
336 42 Patrice Nadeau
* @brief Vérifie si une horloge est est initialisée
337 76 Patrice Nadeau
* @param[in] nb Timer number. @n Valeurs possibles :
338 24 Patrice Nadeau
* − @arg **TIMER_1**
339
* − @arg **TIMER_2**
340 1 Patrice Nadeau
* @return
341
* @retval true Horloge *nb* est initialisée
342 42 Patrice Nadeau
* @retval false Horloge *nb* n'est PAS initialisée
343 1 Patrice Nadeau
* @pre init_timer
344 102 Patrice Nadeau
* @post N/A
345 1 Patrice Nadeau
**/
346
static bool is_timer_set(uint8_t nb);
347
348
```
349
350
## Items déconseillés et retirés
351 59 Patrice Nadeau
352 76 Patrice Nadeau
Les fonctions et variables ne devant plus être utilisés, DOIVENT générer un message lors de la compilation (`-Wall`) si un appel est effectué.
353 80 Patrice Nadeau
* Les attributs`deprecated` ou `unavailable` DOIVENT être ajoutés à la déclaration.
354 1 Patrice Nadeau
* La documentation DOIT indiquer les substituts à utiliser.
355 59 Patrice Nadeau
356
Exemple :
357
``` c
358
/**
359
 * @brief OldFunction
360 76 Patrice Nadeau
 * @deprecated Utiliser NewFunction à la place
361 59 Patrice Nadeau
 * @since Version x.x.xx
362
 */
363 84 Patrice Nadeau
int OldFunction(void) __attribute__((deprecated));
364 59 Patrice Nadeau
365
/**
366
 * @brief OldFunction
367 76 Patrice Nadeau
 * @deprecated Utiliser NewFunction à la place
368 1 Patrice Nadeau
 * @since Version x.x.xx
369 59 Patrice Nadeau
 */
370 84 Patrice Nadeau
int OldFunction(void) __attribute__((unavailable));
371 59 Patrice Nadeau
```
372 11 Patrice Nadeau
373
## Préprocesseur
374 1 Patrice Nadeau
Directives du préprocesseur gcc.
375
376
### #include
377
378 43 Patrice Nadeau
Pour inclure d’autres fichier comme les fichiers entête.
379 1 Patrice Nadeau
380
### #ifdef / ifndef
381
382 76 Patrice Nadeau
Surtout utilisé pour des options de compilation sur différentes plateforme.
383 1 Patrice Nadeau
Utiliser une forme évitant les répétitions.
384
385
> N’est pas documenté dans Doxygen.
386
387
Exemple :
388
```c
389
const char BLUE =
390
  #if ENABLED(FEATURE_ONE)
391
    '1'
392
  #else
393
    '0'
394
  #endif
395
;
396
```
397
398
### Diagnostiques
399
400 78 Patrice Nadeau
Les macros `#warning` et `#error` sont utilisées pour afficher des avertissements ou des erreurs lors de la compilation.
401 1 Patrice Nadeau
402
> Ne sont pas documentées dans Doxygen.
403
404
Exemple :
405
``` c
406
#ifndef usart_AVR
407
    #error "__FILE_NAME__ is not supported on this AVR !"
408
#endif
409
410
#ifndef __test__
411
    #warning "test is not defined !"
412
#endif
413
```
414
415
### Définitions
416
417
Un `#define` est utilisé pour remplacer une valeur au moment de la compilation
418
> Pour la définition d'une valeur « integer », un `enum` DOIT être utilisé.
419
420
Exemple :
421
``` c
422
/**
423 76 Patrice Nadeau
* @name Nom des registres
424 1 Patrice Nadeau
*/
425
/** @{ */ 
426
/** @brief USART1 */
427
#define USART1 REG1
428
/** @brief USART2 */
429
#define USART2 REG2
430
/** @} */
431
432
USART1 = 0x0F;
433
```
434
435
## Atmel AVR
436
437
Particularités pour les microcontrôleurs 8 bits AVR d’Atmel.
438
439
[Atmel AVR4027: Tips and Tricks to Optimize Your C Code for 8-bit AVR Microcontrollers](https://ww1.microchip.com/downloads/en/AppNotes/doc8453.pdf)
440
441
### Fichier d’en-têtes
442
443 25 Patrice Nadeau
Vérification du modèle de microcontrôleur
444
    > Via l'option `-m` de [gcc](https://github.com/embecosm/avr-gcc/blob/avr-gcc-mainline/gcc/config/avr/avr-mcus.def)
445
446 1 Patrice Nadeau
```c
447 25 Patrice Nadeau
#ifndef defined (__AVR_ATmega48__) || (__AVR_ATmega48P__) || \
448
	(__AVR_ATmega88P__) || defined (__AVR_ATmega88__) || \
449
	(__AVR_ATmega168__) || defined (__AVR_ATmega168P__) || \
450
	(__AVR_ATmega328__) || defined (__AVR_ATmega328P__)
451
#warning "Cette librairie n'as pas été testée sur cette famille de microcontrôleur."
452
#endif
453 1 Patrice Nadeau
```
454
455
### Macros
456 45 Patrice Nadeau
457
Définis dans le fichier `config.h`
458
459
Liste : 
460 1 Patrice Nadeau
* `F_CPU` : La fréquence utilisée par l'horloge (interne ou externe) du microcontrôleur
461
462
    > Les « fuses » doivent correspondent à la bonne source de l'horloge.
463
464
### Types
465
466
De nouveau type d'entier sont fournis avec la librairie `<stdint.h>`.
467
468
L'utilisation de ces types DOIT être utilisé afin d'exprimer le nombre de bit d'un objet.
469
470
### Progmem
471 44 Patrice Nadeau
472
<https://www.avrfreaks.net/s/topic/a5C3l000000U5SFEA0/t034767>
473
474 1 Patrice Nadeau
Pour mettre des variables en lecture seule dans la section FLASH au lieu de SRAM avec `<avr/pgmspace.h>`.
475
> L’accès à ces variables est faite via les macros de la librairie.
476
477
Le nom de la variable DOIT être suivie de **_P**
478
479
Exemple :
480
```c
481
#include <avr/pgmspace.h>
482
...
483
/** @brief Variable en FLASH */
484
const int Variable1_P PROGMEM = 42;
485
```
486
487
### Fonction main
488
Un microcontrôleur AVR ne termine jamais la fonction `main`.
489
490
* Déclarer la fonction main avec l’attribut `noreturn`
491
* La boucle sans fin la plus optimisé est le `for (;;)`
492
493
Justification : [AVR035](https://ww1.microchip.com/downloads/en/AppNotes/doc1497.pdf)
494
495
Exemple :
496
```c
497 26 Patrice Nadeau
#include <avr/io.h>
498
499 1 Patrice Nadeau
/** 
500
 * @brief Never ending loop
501
*/
502 83 Patrice Nadeau
void main(void) __attribute__((noreturn));
503 1 Patrice Nadeau
504
/* main function definition */
505 9 Patrice Nadeau
void main(void) {
506 1 Patrice Nadeau
    ...
507
    /* never return */
508
    for (;;) {
509
    };
510
};
511
```
512
513 70 Patrice Nadeau
### Opérations « atomiques »
514 69 Patrice Nadeau
Opérations ne devant pas être interrompus, comme charger un registre de 16 bits avec un registre de 8 bits.
515 1 Patrice Nadeau
516
La librairie `avr-libc` (util/atomic.h) fournit des macros permettant la gestion entre autre des interruptions.
517
518
Les instructions critiques sont insérées dans un `ATOMIC_BLOCK`.
519
520
Exemple :
521
```c
522 72 Patrice Nadeau
#include <util/atomic.h>
523 1 Patrice Nadeau
...
524
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
525
    ...
526
}
527
...
528
```