强符号和弱符号
? ? ? ? ? ?在C語言中,函數和初始化的全局變量(包括顯示初始化為0)是強符號,未初始化的全局變量是強符號。關于多個強弱符號定義類型不一致的主要有下面三種情況:
1.兩個或兩個以上強符號類型不一致
2.有一個強符號,其他都是弱符號
3.兩個或兩個以上弱符號類型不一致
對于情況一,編譯會報符號重定義錯誤。
?
對于情況二,鏈接最終會選擇強符號。示例代碼如下:
?
[mapan@localhost 2]$ cat a.c #include <stdio.h>int shared;int main() {int a = 100;swap(&a,&shared);return 0; } [mapan@localhost 2]$ cat b.c #include <stdio.h>int shared = 2;void swap(int *a,int *b) {*a *= *b;printf("a = %d\n",*a); } [mapan@localhost 2]$ gcc a.c b.c [mapan@localhost 2]$ ./a.out a = 200 [mapan@localhost 2]$?
編譯沒報錯,并且打印出正確結果。鏈接取的強符號(已初始化的全局變量)。這是強弱符號類型一樣的情況,強弱符號類型不一下的情況如下:
?
[mapan@localhost 2]$ cat a.c #include <stdio.h>long shared = 1;int main() {printf("%d\n",shared);return 0; } [mapan@localhost 2]$ cat b.c #include <stdio.h>int shared ;[mapan@localhost 2]$ gcc a.c b.c [mapan@localhost 2]$ ./a.out 1 [mapan@localhost 2]$?
編譯正常。這是強類符號的大小大于弱類型符號大小。再看:
?
[mapan@localhost 2]$ cat a.c #include <stdio.h>long shared ;int main() {printf("%d\n",shared);return 0; } [mapan@localhost 2]$ cat b.c #include <stdio.h>int shared = 1;[mapan@localhost 2]$ gcc a.c b.c /usr/bin/ld: Warning: alignment 4 of symbol `shared' in /tmp/ccNlFnUp.o is smaller than 8 in /tmp/ccp5HfsC.o /usr/bin/ld: Warning: size of symbol `shared' changed from 8 in /tmp/ccp5HfsC.o to 4 in /tmp/ccNlFnUp.o [mapan@localhost 2]$ ./a.out 1 [mapan@localhost 2]$編譯產生警告信息,這是因為2個目標文件的COMMON塊不一致(未初始化的全局變量存放在COMMON塊)。當不同的目標文件需要COMMON塊空間大小不一致時,以最大的那塊為準。
?
?
對于情況三,編譯正常,沒啥好說的了。
?
?
?
?
?
?
?
?
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: 目标文件中的几个重要的段
- 下一篇: 水平和边缘触发实战