# Help with defining external constants

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

## Recommended Posts

I want a constant to be defined over all files in my project. Let's say I have two source files, and a header file. In the header file, I define the constants, but I don't know where to put extern, and supposedly I have to define them in another source file as well...can anyone help?

##### Share on other sites
why would you want extern? use static const type var = whatever in the header

##### Share on other sites
You'll have a header file that declares the variable without defining it. Any source file that wants to use that global variable will have to include this header file. The header file will have a matching source file which actually defines the variable. Here's how you set it up:

global.h
extern int foo;

global.cpp
int foo = 7;

The declaration in the header file which is marked with extern merely lets other source files know that a variable with that name is defined somewhere in another source file in the project. When the seperate source files are compiled and linked, all references to that variable will be linked to the variable of the same name in global.cpp, which is the only actual definition of the variable. Generally speaking, you should usually initialize this variable to something. The header file will of course have an include guard and all that jazz too.

##### Share on other sites
If they are truly constants then you don't need an extern: as Gink says just use a static const (or a #define if you prefer the C way of doing things). If you want a global variable that can be changed you need to do what Nemesis2k2 describes.

##### Share on other sites
Oh right, constant. I missed that part. :)

##### Share on other sites
Assuming C++, the declaring a const static in a header is unnecessary. const variables implicitly have internal linkage, so do not need to be declared static. So in the header all you need is:

const int foo = WHATEVER;

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 11
• 11
• 15
• 11
• 11
• ### Forum Statistics

• Total Topics
634149
• Total Posts
3015834
×