Global Constants and External Arrays

closed account (49iURXSz)
Hello everyone.

I'm having trouble building my dice application ( github.com/lmwunder/Fishy-Dice ). I want to be able to use a bunch of global constants that are defined in my progConfig.hpp file ( which they're currently declared to get by the problem I'm having now ) all across my project. However, on one side of the coin, I get issues with the following code setup ( note these are excerpts ):

progConfig.hpp
1
2
extern const int DIE_TYPES;	// The number of unique die types
extern const int DIE_TO_DRAW;	// The number of die players must posess to roll 


playGame.cpp has the playGame() function that uses the above
1
2
3
4
5
6
#include "progConfig.hpp"
playGame()
{
    Dice drawnDie[DIE_TO_DRAW];    // Hold's the drawn die from the cup ( max of three )
    int rollResults[DIE_TO_DRAW] =	// Hold's the results of rolling each dice
}


progData.cppHolds the declarations for the global constants
1
2
3
#include "progConfig.hpp"
const int DIE_TYPES = 3;    // Number of Die Types
const int DIE_TO_DRAW = 3;  // Number of die for player to draw 


The constants in playGame() are undefined at compile time, which means that the arrays in that function are useless...

On the other side of the coin however, by defining the constants in the progConfig.hpp file, I will get multiple copies of the same variable, which also gives me an error ( a linker error though when I try to build ).

My environment is a Visual Studio 2012 IDE (sadly)...
Honestly I would suggest not doing something so complex. Generally people declare their constants inside a class, or in the file which they are used.

However, my guess on how to fix this would be to use a #define DIE_TO_DRAW 3 instead.

You can also put your constants inside a class as a static constant variable.

-Blueberry
> On the other side of the coin however, by defining the constants in the progConfig.hpp file,
> I will get multiple copies of the same variable, which also gives me an error

Define the constants in the header file progConfig.hpp

By default, they have internal linkage, and won't give you a linker error.
(Do not change the default linkage with the extern keyword)

1
2
3
4
// progConfig.hpp

/* extern */ const int DIE_TYPES = 3 ; // The number of unique die types
/* extern */ const int DIE_TO_DRAW = 3 ; // The number of die players must posess to roll 


Or C++11 (I'm not sure if Visual Studio 2012 compiler supports constexpr):
1
2
3
4
// progConfig.hpp

constexpr int DIE_TYPES = 3 ; // The number of unique die types
constexpr int DIE_TO_DRAW = 3 ; // The number of die players must posess to roll 
Last edited on
closed account (49iURXSz)
So all constants have internal linkage in C++ throughout the entire project? Ok, thanks!
Topic archived. No new replies allowed.