I have a question regarding weak attribute of const variable. I have the following couple of files compiled with gcc:
main.c:
#include
The identifiers have internal linkage. This is an obsolecense feature (static
storage class specifier should be used). In general, you should have a header with an extern
declaration of the identifier:
extern const int my_var;
Linking with different qualifiers is a bad idea.
Maybe the better understandable approach is to use wekref
plus alias
.
I faced the same issue (cf. GCC optimization bug on weak const variable) and came up with the conclusion that gcc
does not handle well the optimization on the weak
/const
variable within the file where the weak definition is: in your 'main.c' file, my_var
is always resolved to 100
.
Not sure, but it seems to be a gcc
bug (?).
To solve this, you can :
-O0
option to gcc
.
-O0
should be the default value, so this might not help...const
keyword as you did: gcc
cannot optimize no more as my_var
can potentially change now.const int my_var __attribute__((weak)) = 100;
statement in a separate source file ('main_weak.c' for instance): while building 'main.c', gcc
does not know the my_var
value and thus won't optimize.