c語言中函式存盤在哪里?誰能用簡單的語言解釋一下?
#include stdio.h>
void g()
{
int a=7;
}
int main()
{
printf("%d\n",sizeof(g()));
printf("%p",&g);
return 0;
}
以下程式的輸出是
1
00007ff6ee001581
以及函式內部變數的存盤位置并與函式地址鏈接
uj5u.com熱心網友回復:
函式內部的變數存盤在堆疊中。
每個鏈接和尋址部分都是由聯結器完成的。
簡單來說,聯結器決定給什么標簽或函式提供什么絕對地址,編譯器決定它們將如何排列并能夠相互尋址。
編譯需要四個步驟:
Preprocessing [in which header file and microprocessor worked upon].
Compiling[In which they are converted into assembly code]
Assembly[In which codes are converted into machine level language but have relative addressing in respect to there starting]
Linking[When absolute address is given so when loaded they can address each other and files and linked in one]
#我認為這些最后幾行可以幫助你
函式和變數都是標簽,每個標簽都被翻譯成地址。在機器上運行的代碼具有代表這些標簽的地址。不僅是 c,而且每一種編譯語言都會經歷它。在機器上,它的機器代碼或只是接線。
如果你什么都不懂就說。很樂意幫助你
uj5u.com熱心網友回復:
以下程式的輸出是
輸出的第二行是指向函式代碼的指標g。這是該函式的地址,它是您關于函式存盤位置的問題的答案。
以及函式內部變數的存盤位置并與函式地址鏈接
該變數a是一個區域變數,所以它只在函式執行時存在。通常編譯器會在堆疊上為區域變數創建空間——這是擁有堆疊的主要原因之一。一旦函式回傳,它的區域變數就會從堆疊中彈出并且它們不再存在。換句話說,a根本不連接到的位置g。
區域變數通常通過堆疊指標的一些偏移量來參考。呼叫函式時,會在堆疊上創建一個堆疊幀。堆疊幀基本上由所有函式的區域變數的存盤,以及前一個堆疊指標的地址和回傳地址組成。然后函式的代碼開始執行,因為編譯器知道相對每個變數的地址(即它在堆疊幀中的位置),它可以很容易地計算出絕對地址。正是由于這個原因,大多數處理器都有使相對尋址變得容易的指令。當函式退出時,堆疊指標被設定回前一個堆疊幀,處理器跳轉到回傳地址。但這只是一種可能的實作方式;在具有大量暫存器的現代處理器上,區域變數甚至可能不會存盤在堆疊中——它們可能只是最終存盤在暫存器中。
uj5u.com熱心網友回復:
include <stdio.h>
void g()
{
int a=7;
}
int main()
{
//printf("%d\n",sizeof(g()));
//you cant use sizeof(g()) its a functiona and
//function not have anysize
printf("%p",&g);
//even you can't use here int a=7 that you declared in void g() as it is local to
//that function and this function cant access any function local variable
//but what it returns
return 0;
}
如果您想查看尋址而不是查看以下內容:
0000000000001135 <g>:
1135: 55 push %rbp
1136: 48 89 e5 mov %rsp,%rbp
1139: c7 45 fc 07 00 00 00 movl $0x7,-0x4(%rbp)
1140: 90 nop
1141: 5d pop %rbp
1142: c3 retq
0000000000001143 <main>:
1143: 55 push %rbp
1144: 48 89 e5 mov %rsp,%rbp
1147: 48 8d 35 e7 ff ff ff lea -0x19(%rip),%rsi # 1135 <g>
114e: 48 8d 3d af 0e 00 00 lea 0xeaf(%rip),%rdi # 2004
<_IO_stdin_used 0x4>
1155: b8 00 00 00 00 mov $0x0,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438958.html
