Tips when defining global constant in header file
Options of defining global constant in header file
#define GLOBAL_CONST_VAR 0xFF
const int GLOBAL_CONST_VAR = 0xFF;
extern const int GLOBAL_CONST_VAR;
and in one source file usescosnt int GLOBAL_CONST_VAR = 0xFF;
According to Effective C++, ITEM 2:
Prefer
const
,enum
, andinline
to#define
.
So option 1 is not preferred (which I particularly like to use). In my project, I have a header file that uses three constant string.
1 | // util.hpp |
However, when I run the makefile, it has the error goes like:
1 | /usr/bin/ld: player.o:/home/fg96/ECE650/HW3/util.hpp:14: multiple definition of `CLIENT_CONNECT_CONFIRM'; util.o:/home/fg96/ECE650/HW3/util.hpp:14: first defined here |
Which clearly indicates that the CLIENT_CONNECT_CONFIRM
are regarded not as the constant, but variable, but why? Reason is that
const char * ...
is not constant, because
const char *
means that the value pointer points to cannot
change, but the value of the pointer can change (very silly
mistake).
The following definition will be just fine:
1 | // all const pointers pointing to const values |
Since C++17, inline
specifier can also be used on
variable. According to the cppreference:
An inline function or variable(since C++17) with external linkage (e.g. not declared static) has the following additional properties: There may be more than one definition of an inline function or variable(since C++17) in the program as long as each definition appears in a different translation unit and (for non-static inline functions and variables(since C++17)) all definitions are identical. For example, an inline function or an inline variable(since C++17) may be defined in a header file that is included in multiple source files.
But we are not allowed to use c++17 so ...
Another possibility would be to use namespace 1
2
3namespace {
char * CLIENT_CONNECT_CONFIRM = "CLIENT_CINFIRM";
}
Reference
Tips when defining global constant in header file