GCC weak attribute on constant variables

后端 未结 2 1525
你的背包
你的背包 2021-01-14 07:20

I have a question regarding weak attribute of const variable. I have the following couple of files compiled with gcc:

main.c:

#include 

        
相关标签:
2条回答
  • 2021-01-14 07:42

    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.

    0 讨论(0)
  • 2021-01-14 07:49

    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 :

    • prevent optimization, by adding the -O0 option to gcc.
      • -O0 should be the default value, so this might not help...
    • get rid of the const keyword as you did: gcc cannot optimize no more as my_var can potentially change now.
    • set your 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.
    0 讨论(0)
提交回复
热议问题