糊涂了很久,看了别人的解释,似懂非懂的。今天终于看了stackoverflow里面的解释。自己写了点程序验证了下,终于明白了。
局部变量:作用域在一个block里
例如
{
int i = 0;
}
i就是局部变量,作用域就在大括号里。
再看
{
i = 0;
}
局部变量实质在存放在函数的栈中,每一次invoke函数,都会产生变量i,多次调用i之间是不受影响的。
void f();
int main()
{
f();
f();
return 0;
}
void f()
{
std::string localA;
localA += "ab";
std::cout << localA<<"\n";
}
例子:
void f();
int main()
{
f();
f();
return 0;
}
void f()
{
static std::string localA;
localA += "ab";
std::cout << localA<<"\n";
}
全局变量存放地和静态变量一致,但是作用域是定义全局变量的文件scope。如果其他文件需要使用这个变量,需要用extern声明。
全局静态变量同样存放在global里,但是其作用域在translation unit。
下面是关于translation unit的解释:本source文件+include的文件。
A translation unit is the basic unit of compilation in C++. It contains:
- all the contents of a single source file after the preprocessor has run its course
- the contents of any header files directly or indirectly included by it
- minus any lines ignored using conditional preprocessing statements
A single translation unit gets compiled into an object file, library, or executable program.
A source file, by contrast, is a stand-alone file, just like any other file on your file system. Once compiled, it can be a component of a translation unit as mentioned above.