Constant variables defined in the header, computed multiple times at compile time
Consider the following header file, which consists of a slow constexpr function that is used to initialize a global variable:
constexpr int slow_func() {
for (int i = 0; i < 100*1024*100; ++i)
;
return 0;
}
constexpr int g_val = slow_func();
Calling this function takes ~ 10 s
Now if this title gets # included in multiple translation units, build time is increased for each translation unit that # includes this file
With hundreds of translation units, compilation now takes an unreasonable amount of time.
Since this is a constexpr function, I assumed that the compiler would evaluate the return value of this function only once and use the same value in different translation units
Is there a way to tell the compiler to evaluate the value of each "g_val" only once? If not, what can be done?
I'm currently using g ++ - 5.4, but I suppose the standard specifies this behavior (although I didn't find it in the current standard)
source to share
Because of the way #include works, you'd be better off making the variable somewhere once, and then making it a forward-declared global variable (by #include forw. Dec.) In all your translation units. This means it only needs to compile once, but anywhere it declares can use it.
Of course, this will be a global variable, so there are downsides. But making it global should stop recompiling it.
source to share