C++ 静态局部函数与全局函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14742664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ static local function vs global function
提问by Arun
What is the utility of having static functions in a file ?
在文件中使用静态函数有什么用?
How are they different from having global functions in a file ?
它们与在文件中具有全局函数有何不同?
static int Square(int i)
{
return i * i;
}
vs
对比
int Square(int i)
{
return i * i;
}
回答by dasblinkenlight
What is the utility of having static functions in a file?
在文件中包含静态函数有什么用?
You can use these functions to provide shared implementation logic to other functions within the same file. Various helper functions specific to a file are good candidates to be declared file-static.
您可以使用这些函数为同一文件中的其他函数提供共享的实现逻辑。特定于文件的各种帮助函数是声明文件静态的良好候选者。
How are they different from having global functions in a file?
它们与在文件中具有全局函数有何不同?
They are invisible to the linker, allowing other compilation units to define functions with the same signature. Using namespaces alleviates this problem to a large degree, but file-static
functions predate namespaces, because they are a feature inherited from the C programming language.
它们对链接器不可见,允许其他编译单元定义具有相同签名的函数。使用命名空间在很大程度上缓解了这个问题,但文件static
函数早于命名空间,因为它们是从 C 编程语言继承的特性。
回答by Charles Salvia
A static
function simply means that the linker cannot export the function (i.e. make it visible to other translation units). It makes the function "private" to the current translation unit. It is the same as wrapping the function in an anonymous namespace.
一个static
功能简单的说就是链接器无法导出功能(即使其对其他可见的翻译单元)。它使函数对当前翻译单元“私有”。这与将函数包装在匿名命名空间中是一样的。
namespace {
int Square(int i)
{
return i * i;
}
}
Generally, using an anonymous namespace is the preferred C++ way of achieving this, instead of using the static
keyword.
通常,使用匿名命名空间是实现此目的的首选 C++ 方式,而不是使用static
关键字。
回答by Leo supports Monica Cellio
Static functions are visible on the file where they were defined only. You can't refer to them outside of that particular file.
静态函数仅在定义它们的文件中可见。您不能在该特定文件之外引用它们。
回答by Yuushi
In a word, linkage. static
functions have internal linkage, that is, they aren't visible outside of their translation unit.
一句话,联动。static
函数具有内部链接,也就是说,它们在其翻译单元之外是不可见的。