• Advertisement
Sign in to follow this  

Using Constants in Headers

This topic is 1977 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello,

I have been running into a problem in my code lately. I have a file called "Constants.h" and one called "Constants.cpp." I define all my constants there. However, when I include Constants.h in another .h file I always get compile errors when, for example, trying to allocate arrays of a GIVEN_CONSTANT size. Is there a reason for this? I never get these errors in .cpp files. It seems like the pre-processor is not expanding my #includes into the header, or maybe there is a rule that constants can't be used in headers in c++? Can someone shed some light on this situation for me?

Thanks.

- Dave Ottley

Share this post


Link to post
Share on other sites
Advertisement
I'll give you an example. This is not exact because I have already fixed the errors with a workaround. But, for example

Constants.h:
extern const int MAX_INTS;

Constants.cpp
extern const int MAX_INTS = 1000;

Foo.h
#include "Constants.h"
class Foo {
int bar[MAX_INTS];
void DoSomething();
};

Compiler Error: "Arrays must be initialized with a constant."

*NEW* Foo.h
#include "Constants.h"
const int MAX_INTS = 1000;
class Foo {
int bar[MAX_INTS];
void DoSomething();
};

Compiles fine. Edited by KingofNoobs

Share this post


Link to post
Share on other sites
First of all, in your Constants.cpp file you need to write "const int MAX_INTS = 1000; "
The extern keyword means "declare without defining". In other words, it is a way to explicitly declare a variable, or to force a declaration without a definition.

The practice itself (putting the initialization into the cpp file) is a matter of personal taste. I personally like it because if i need to change the value for whatever reason, not every single file which includes the header file is compiled again.

But i wouldnt use "extern" anymore....i like static const uint32 MAX_INTS; in a header file more. ;-)

Share this post


Link to post
Share on other sites
Thank you all for your comments. I have decided to go with the

#ifndef
#define MAX_INTS 1000
#endif

route because it doesn`t waste any memory. I can`t see a downside to it either, and this is how the Microsoft .h files are organized. Until next time...

- Dave Ottley

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement