what is the difference between “constexpr” and “static constexpr” variables of the non-class type in a header file?

牧云@^-^@ 提交于 2019-12-24 01:53:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!