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

## 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 on other sites
It would help to see what your code actually looks like and what compiler errors you're actually getting.

##### Share on other sites
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 on other sites
Why aren't you putting the constants in the header?

##### 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 on other sites
. Edited by C0lumbo

##### 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 doesnt waste any memory. I cant see a downside to it either, and this is how the Microsoft .h files are organized. Until next time...

- Dave Ottley

1. 1
Rutin
29
2. 2
3. 3
4. 4
5. 5

• 13
• 13
• 11
• 10
• 13
• ### Forum Statistics

• Total Topics
632959
• Total Posts
3009468
• ### Who's Online (See full list)

There are no registered users currently online

×