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 0xFFint GLOBAL_CONST_VAR = 0xFF;- Some function returing the value (e.g.
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 fileconst 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:
- What do you prefer (5) or (6)?
- Why (5) is ok, while (2) is not?
(5) says exactly what you want to say. Plus it lets the compiler optimize it away most of the time. (6) on the other hand won’t let the compiler ever optimize it away because the compiler doesn’t know if you’ll change it eventually or not.