Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ best way to define cross-file constants

I am working on a game and have an interesting question. I have some game-wide constant values that I want to implement in one file. Right now I have something like this:

constants.cpp

extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;

constants.hpp

extern const int BEGINNING_HEALTH;
extern const int BEGINNING_MANA;

And then files just #include "constants.hpp" This was working great, until I needed to use one of the constants as a template parameter, because externally-linked constants are not valid template parameters. So my question is, what is the best way to implement these constants? I am afraid that simply putting the constants in a header file will cause them to be defined in each translation unit. And I don't want to use macros.

Thanks

like image 511
rlbond Avatar asked Mar 13 '09 03:03

rlbond


2 Answers

Get rid of the extern and you're set.

This code works perfectly fine in a header, because everything is "truly constant" and therefore has internal linkage:

const int BEGINNING_HEALTH = 10;
const int BEGINNING_MANA = 5;
const char BEGINNING_NAME[] = "Fred";
const char *const BEGINNING_NAME2 = "Barney";

This code cannot safely be put in a header file because each line has external linkage (either explicitly or because of not being truly constant):

extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;
const char *BEGINNING_NAME = "Wilma";  // the characters are const, but the pointer isn't
like image 158
Tom Avatar answered Oct 09 '22 00:10

Tom


How about enums?

constants.hpp

  enum {
    BEGINNING_HEALTH = 10,
    BEGINNING_MANA = 5
  }
like image 32
Tommy Hui Avatar answered Oct 08 '22 23:10

Tommy Hui