Search code examples
cconstantsheader-filescompile-time-constant

Externally defined constant in C header file


I have a struct that is defined within a header file that contains a 2D array (lanes). I would like to define the size of the array at compile time, for example by setting an environment variable.

#ifndef GAMEBOARD_H
#define GAMEBOARD_H

struct gameboard
{
    int lanes[4][4];
    int isWonBy;
    int isFinished;
    int nextPlayer;
};

struct gameboard *put(struct gameboard *board, int laneIndex);

#endif

I want to keep the array at a constant size during runtime between all instances of this struct, but define what that size is at compile time without having to change the source code every time. Height and width of the array should be seperate and also have default values.


Solution

  • #ifndef LANES_DIMENSION
    #error "You must define LANES_DIMENSION at compile time!"
    #endif
    
    struct gameboard
    {
        int lanes[LANES_DIMENSION][LANES_DIMENSION];
        int isWonBy;
        int isFinished;
        int nextPlayer;
    };
    

    GCC:

    gcc -DLANES_DIMENSION=10 source.c
    

    MSVC:

    cl /DLANES_DIMENSION=10 source.c