2012-11-12 75 views
2

我想知道編譯器內部會發生什麼...... 就像它是否將全局變量存儲在不同的位置一樣。編譯器如何知道某個變量是全局變量還是本地變量(C)

+4

給自己一本關於編譯器基礎知識的好書。可能在這裏獲得一些資源 - http://stackoverflow.com/questions/1669/learning-to-write-a-compiler – CCoder

+0

獲取任何關於C或C++的書。得到了關於* scope *的章節。 –

+0

@honk一個變量可以是一個全局變量,但不在全局範圍內......範圍和生命期是不同的。 (假設這就是你的意思) –

回答

0

它知道該變量是全局的還是本地的,通過聲明它。

//declared at namespace scope - global 
extern int x;  

int main() 
{ 
    //declared inside a method - local 
    int y; 
}; 
+0

評論對downvotes? –

3

符號表上的維基百科頁面可以爲您提供基本的瞭解。

http://en.wikipedia.org/wiki/Symbol_table

在計算機科學中,符號表是由一個 語言翻譯器使用的數據結構,諸如編譯器或解釋,其中每個 標識符在一個程序的源代碼與信息 與相關聯的到其聲明或外觀的來源,,如其 類型,範圍級別,有時它的位置。

[...]

常見的實施方法是使用哈希表 實現。 對於所有的 符號,編譯器可以使用一個大符號表,或對不同的 作用域使用分離的分層符號表。

強調我的。

0

通常有4個範圍內的任何變量。 使用你正在該變量的extern明確。extern關鍵字(默認爲全局變量extern

使用static限制變量或函數範圍,它是當前文件

按照該內存在不同的分配段

 global: visible in more than one source file 
-- data segement(also differs whether initialised or uninitialized) 


     local : visible with in { } it also called function(){} scope 
-- on stack 


     block : {} inside any function another scope of block valiables with in {} 

    -- on stack if with in function 


     file : making static variable is limited to it's file scope or 
    current translation unit. -- again data section