I want to define a constant in C++ to be visible in several source files. I can imagine the following ways to define it in a header file:
#define GLOBAL_CONST_VAR 0xFF
int GLOBAL_CONST_VAR = 0xFF;
int get_GLOBAL_CONST_VAR()
)enum { GLOBAL_CONST_VAR = 0xFF; }
const int GLOBAL_CONST_VAR = 0xFF;
extern const int GLOBAL_CONST_VAR;
and in one source file const int GLOBAL_CONST_VAR = 0xFF;
Option (1) - is definitely not the option you would like to use
Option (2) - defining instance of the variable in each object file using the header file
Option (3) - IMO is over killing in most cases
Option (4) - in many cases maybe not good since enum has no concrete type (C++0X will add possibility to define the type)
So in most cases I need to choose between (5) and (6). My questions:
The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.
A constant is a name given to the variable whose values can't be altered or changed. A constant is very similar to variables in the C programming language, but it can hold only a single variable during the execution of a program.
Global Constants. A global constant is a literal value to which you assign a name. Like a global variable, you can access the value of the global constant from any script or 4GL procedure in the application. You set the value for the global constant when you declare it.
Definitely go with option 5 - it's type safe and allows compiler to optimize (don't take address of that variable :) Also if it's in a header - stick it into a namespace to avoid polluting the global scope:
// header.hpp namespace constants { const int GLOBAL_CONST_VAR = 0xFF; // ... other related constants } // namespace constants // source.cpp - use it #include <header.hpp> int value = constants::GLOBAL_CONST_VAR;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With