Using globals in headerfiles

Hey, I've just officially joined c++.com after lurking for the past few years.

I've been having trouble with globals in header files in my projects.

I have globals.h:
1
2
3
4
static int MIN_X = 1;
static int MAX_X = 100;
static int MIN_Y = 1;
static int MAX_Y = 100;


And I am trying to make a class in class.h:
1
2
3
class Board{
int board[MAX_X + 2][MAX_Y + 2];
};

But that throws an error:
"data member may not have variably modified type `int[(((unsigned int)(((int)MAX_X) + 1)) + 1u)][(((unsigned int)(((int)MAX_Y) + 1)) + 1u)]'|

How should I go about fixing it? I need MAX_X, MAX_Y in other files as well, and I want the Board class to be more dynamic in case I change it later.

Thanks
Last edited on
I've been having trouble with globals in header files
Don't define global variables in header files.

You seem to need constants rather than varaibles, so your code C++ ought to be:
1
2
3
4
const int MIN_X = 1;
const int MAX_X = 100;
const int MIN_Y = 1;
const int MAX_Y = 100;
or if you're using C:
1
2
3
4
#define MIN_X  1
#define MAX_X 100
#define MIN_Y 1
#define MAX_Y 100 

Last edited on
Wow. Thanks
I usually do use const, but I swear I got errors from it so I used static.
It's working fine now :P
closed account (1yR4jE8b)
If you want these variables available in other files why not make them static in the Board class? Doing it this way makes the code a bit clearer as well (imo), and you don't have to deal with the global variable issues.;

Board.h
1
2
3
4
5
6
class Board {
public:
  static const int MIN_X = 1, MAX_X = 2, MIN_Y = 1, MAX_Y = 100;
private:
  int board[MAX_X + 2][MAX_Y + 2];
};


main.cpp
1
2
3
4
5
6
7
8
#include <iostream>
#include "Board.h"

int main() {
  //ok I need MAX_X
  int x = Board::MAX_X;
  return 0;
}

Topic archived. No new replies allowed.