強符號和弱符號

ref: http://yonghaowu.github.io/2016/05/09/Relocation_Symbol_Decoration/



/* bar2.c */
#include <stdio.h>


 double x;
 void f() 
{
 printf(" &x=%x\n", &x );
 x = 1; 
}


/* foo2.c */
 #include <stdio.h>
 void f(void);
 int x = 1234;
 int y = 5678;
 int main()
{
 f();
 printf("&x=%x, &y=%x\n", &x, &y );
 printf("x = 0x%x y = 0x%x \n", x, y);
 return 0;
}


 ./a.out
 &x=601040
&x=601040, &y=601044
x = 0x0 y = 0x3ff00000 


//1的double類型表示就是:3FF0000000000000,表示運行主機是小端字節序
// nm -S bar2.o可以查看到x佔8個字節
這裏, foo2.c中的x跟y都是強符號, 而bar2.c中的x是弱符號, 鏈接器選擇了foo2.c中的x. 而在bar2.c 中的 f函數中賦值時, 就是給for2.c中的int x賦值. 在一臺IA32機器上, double類型是8個字節, 而int類型是4個字節, 因此bar2.c的x=-0.0會覆蓋了x跟y的位置. (x跟y在foo2.c中佔8個字節, 而在bar2.c中的強符號就佔了8個字節, 執行f函數賦值爲-0.0時就覆蓋了x跟y的位置了)



/* 測試字節序
#include <stdio.h>


union A
{
int a;
char buf[4];
}t;




int main()
{
int ret = 0;
t.buf[0] = 0;
t.buf[1] = 0;
t.buf[2] = 0;
t.buf[3] = 'A';


int i = 0;


printf("%d\n", t.a );
for( i = 0; i < 4; ++i )
{
//printf( "%c", t.buf[i] );
}

return ret;
}


*/
發佈了94 篇原創文章 · 獲贊 69 · 訪問量 112萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章