How to prevent static const optimization

Is it possible to prevent the optimization of static constant constants using compiler command line options?

Here is an example:

template <unsigned v1> struct TRAITS { static const unsigned val1 = v1; }; template < class TRAITS > struct foo { static const unsigned x1 = TRAITS::val1; }; int main () { foo<TRAITS<1>> f1; // SET BREAKPOINT HERE return 0; } 

Compile:

 g++ -g -O0 optimize_out.cpp 

Gdb:

 gdb a.out (gdb) break optimize_out.cpp:13 (gdb) r (gdb) p f1 $1 = {static x1 = <optimized out>} 

What is characteristic of this code is that classes are templates. Perhaps there is something in the C ++ standard that makes the compiler optimize fields, even with -O0? When I do not use templates, the values ​​are not optimized:

 struct foo { static const unsigned x1 = 1; }; 

In this case, I see x1 in the debugger

+7
source share
1 answer

You can use the used attribute to tell the compiler to give a definition, even if nobody needs it:

 template <unsigned v1> struct TRAITS { static const unsigned val1 [[gnu::used]] = v1; }; template < class TRAITS > struct foo { static const unsigned x1 [[gnu::used]] = TRAITS::val1; }; 

Alternatively, you can add definitions of static variables outside the line (which you will need anyway if you use odr) and add an attribute to these definitions:

 template < class TRAITS > const unsigned foo<TRAITS>::x1 [[gnu::used]]; template <unsigned v1> const unsigned TRAITS<v1>::val1 [[gnu::used]]; 
0
source

Source: https://habr.com/ru/post/1275165/


All Articles