23

static当变量位于 .cpp 文件的全局范围内而不是函数中时,将其标记为 是否有用?

你也可以对函数使用 static 关键字吗?如果是,它们的用途是什么?

4

3 回答 3

20

是的,如果你想声明文件范围变量,那么static关键字是必要的。static在一个翻译单元中声明的变量不能被另一个翻译单元引用。


顺便说一句,static在 C++03 中不推荐使用关键字。

C++ 标准 (2003) 中的 $7.3.1.1/2 部分内容如下:

在命名空间范围内声明对象时,不推荐使用 static 关键字;unnamed-namespace 提供了一个更好的选择。

C++ 更喜欢命名的命名空间而不是static关键字。请参阅此主题:

未命名命名空间优于静态命名空间?

于 2011-01-18T14:32:53.300 回答
18

在这种情况下,关键字 static 表示该函数或变量只能由同一 cpp 文件中的代码使用。关联的符号不会被导出,也不会被其他模块使用。

当您知道其他模块不需要全局函数或变量时,这是避免在大型软件中发生名称冲突的好习惯。

于 2011-01-18T14:32:44.520 回答
1

举个例子——

// At global scope
int globalVar; // Equivalent to static int globalVar;
               // They share the same scope
               // Static variables are guaranteed to be initialized to zero even though
               //    you don't explicitly initialize them.


// At function/local scope

void foo()
{
    static int staticVar ;  // staticVar retains it's value during various function
                            // function calls to foo();                   
}

仅当程序终止/退出时,它们才不再存在。

于 2011-01-18T14:43:02.943 回答