Why uninitialized global variable is weak symbol?

前端 未结 4 2028
一向
一向 2020-12-05 21:30

It seems uninitialized global variable is treated as weak symbol in Gcc. What is the reason behind this?

4条回答
  •  借酒劲吻你
    2020-12-05 21:54

    Is this what you meant?

    weak.c

    #include 
    
    int weak; /* global, weak, zero */
    
    int main(void) {
      printf("weak value is %d.\n", weak);
      return 0;
    }
    

    strong.c

    int weak = 42; /* global, strong, 42 */
    

    Sample run

    $ gcc weak.c
    $ ./a.out
    weak value is 0.
    $ gcc weak.c strong.c
    $ ./a.out
    weak value is 42.

    The int weak; in weak.c is a declaration, not a definition. Or you may say it's a tentative definition. The real definition is in strong.c when that object file is linked in the final program or in weak.c otherwise. This is a common extension, one that gcc uses (thanks Andrey).

提交回复
热议问题