问题
I have a header file test.hxx
which will be included in multiple translation units. The header file is as below:
namespace program_exec
{
static constexpr int DEFAULT_VAL = 0;
static constexpr char *name = "proc_exec";
}
I have included this header file in multiple translation units (*.cxx) and it works fine.
But removing the static infront of constexpr char*
causes a linking error i.e, if I change the static constexpr char *name = "proc_exec"
to constexpr char *name = "proc_exec";
I am getting a linker error saying that
error: multiple definition of program_exec::name
But making the same change for integers works fine i.e, changing static constexpr int = DEFAULT_VALUE;
to constexpr int = DEFAULT_VALUE;
.
Does difference does removing the static**
infront constexpr int
and constexpr char*
makes?
Please help me in understanding the difference. Thank you very much in advance.
[Edit]
Having a variable as a "static constexpr" in a header file and using this header file in multiple translation units. Does each translation unit has its own copy of the variable (or) does the compiler keeps only one copy by optimizing it?
Because using a static variable in a header file with the namespace scope has internal linkage and any translation unit which includes this header file has its own copy of the variable.
Is my understanding correct?
来源:https://stackoverflow.com/questions/42022144/what-is-the-difference-between-constexpr-and-static-constexpr-variables-of-t