Jump to content
  • Advertisement
Sign in to follow this  
Hrothgar15

Help with defining external constants

This topic is 4863 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

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 this post


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

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
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;

Share this post


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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!