Coding Convention

From NCOT Wiki
Revision as of 13:12, 29 July 2025 by Wiki admin (talk | contribs) (Created page with "= C Coding Convention = This convention defines naming and style rules for writing clean, consistent, and self-documenting C code. == General Principles == * Use '''lowercase_with_underscores''' for variables and functions. * Use '''PascalCase''' for struct and enum type names. * Use prefixes to namespace functions and globals by module/library. * Keep names brief but descriptive. == 1. Enums == === Type Name === * Use '''PascalCase''' with an `_e` suffix. <syntaxhi...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

C Coding Convention

This convention defines naming and style rules for writing clean, consistent, and self-documenting C code.

General Principles

  • Use lowercase_with_underscores for variables and functions.
  • Use PascalCase for struct and enum type names.
  • Use prefixes to namespace functions and globals by module/library.
  • Keep names brief but descriptive.

1. Enums

Type Name

  • Use PascalCase with an `_e` suffix.
typedef enum GameState_e {
    GAME_STATE_INIT,
    GAME_STATE_RUNNING,
    GAME_STATE_PAUSED,
    GAME_STATE_EXIT
} GameState_e;

Enum Values

  • Use ALL_CAPS with a common prefix for namespacing.

2. Structs / "Classes"

Type Name

  • Use PascalCase with a `_t` suffix.
typedef struct Player_t {
    int id;
    char name[32];
    float health;
} Player_t;

Member Names

  • Use lowercase_with_underscores.
  • Optionally prefix with struct abbreviation if needed (e.g. `pos_x`, `player_name`).

3. Global Variables

  • Use `g_` prefix.
  • Follow with lowercase_with_underscores.
int g_frame_counter;
bool g_is_debug_mode;
  • For internal linkage, use `static`:
static int g_last_error_code;

4. Functions

General Functions

  • Use lowercase_with_underscores.
  • Use verb_noun structure for clarity.
void init_game();
int calculate_damage(int weapon_id);

Library/Module Functions

  • Prefix with the module name (e.g. `audio_`, `player_`).
// In audio module
void audio_init();
void audio_play_sound(const char *name);

5. Constants / Macros

  • Use ALL_CAPS_WITH_UNDERSCORES.
#define MAX_PLAYERS 16
#define PI 3.14159f

6. File Naming

  • Use `module_name.c` and `module_name.h`.

Examples:

  • `player.c`, `game_state.h`, `audio_mixer.c`

7. Example Summary

// game_state.h
typedef enum GameState_e {
    GAME_STATE_INIT,
    GAME_STATE_RUNNING,
    GAME_STATE_PAUSED,
    GAME_STATE_EXIT
} GameState_e;

// player.h
typedef struct Player_t {
    int id;
    char name[32];
    float health;
    bool is_alive;
} Player_t;

// player.c
Player_t g_main_player;

void player_init(Player_t *player);
void player_take_damage(Player_t *player, float damage);