2012-11-12 38 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