2

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.

N. Elich
  • 23
  • 3
  • You can have your build system fetch the dimensions from the environment (or set the dimensions some other way), and then have the build system set compiler preprocessor flags to define macros for the dimensions, and use those macros in the source. – Some programmer dude Jun 01 '17 at 16:55

2 Answers2

4
#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
fukanchik
  • 2,811
  • 24
  • 29
  • You could also store that value in the struct so it could be inferred at run time... – Grady Player Jun 01 '17 at 17:03
  • I have multiple source files that include this header and use a makefile to compile them. Should I add the -D... argument to the recipe of every file that includes this header (maybe even add it to CFLAGS) or is there a reliable way to know beforehand which file needs to be compiled with this argument? – N. Elich Jun 01 '17 at 17:18
  • Usually people add such flags to `CFLAGS` – fukanchik Jun 01 '17 at 17:32
0

Another method is to have small array_size.h file only for this value. #include it in gameboard.h and re-generate it at compile time e.g. with batch file like:

@echo #define ARRAY_SIZE %ENV_DEF% >array_size.h
i486
  • 6,491
  • 4
  • 24
  • 41