Search code examples
cheaderglobal-variablesextern

Extern, headers, global variables


I'm making a game, the current structure of my program is like the following...

prog structure

The problem I'm having is that I have a function in init_game.c that initialises the players boards with the necessary data, once I have these initialised boards I need the_game.c to use these initialised boards (from init_game.c).

I'm confused on how I would get this to work with extern's

EDIT: Clarification - I'm wondering how I can use the extern keyword with my programs structure to allow me to use the players initialised 2D char array (which gets initialised in the file init_game.c but is first defined in the attributes.h file) in the file the_game.c

Added a picture below for clarification to my problem... enter image description here


Solution

  • In init_game.c, declare global variables,

    char player_board[BOARD_SIZE][BOARD_SIZE];
    char enemy_board[BOARD_SIZE][BOARD_SIZE];
    

    Any file that includes attributes.h will then have access to these arrays, provided that file doesn't declare another variable with the same name.

    In your main, you need to make sure that you call the initializing function from init_game.c before you call any function from the_game.c that uses the global arrays.