Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr variables defined in header evaluated multiple times in compile time

Consider the following header file, which consists of slow constexpr function, which 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 ~10s

Now, if this header gets #included in multiple translation units, the compilation time increases by each translation unit that #includes this file

With hundreds of translations 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 the 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 mandates this behaviour (Even though I didn't find it in the current standard)

like image 928
Mikrosaft Avatar asked Dec 03 '25 04:12

Mikrosaft


1 Answers

Due to how #include works, you'd be better off making the variable somewhere once, then making it a global variable, forward declared(by #including the forw. dec.) in all your translation units. This is so it only has to compile once, but anywhere it's forward declared can use it.

Of course, it'll then be a global variable, so there are downsides to that as well. But making it a global should stop it being recompiled.

like image 115
Apitosu Avatar answered Dec 05 '25 20:12

Apitosu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!