函数定义中可以缺少函数声明中的 static 关键字吗?
我想要一个静态函数,在定义它之前在 .c 文件中声明它:
//file a.c version 1
static int foo();
...
static int foo()
{
...
}
但是,似乎我可以将 static
关键字保留在函数定义之外,并且我不会收到编译器警告。例如,
//file a.c version 2
static int foo();
...
int foo()
{
...
}
我假设这两种形式完全相同吗?
如果是这样,为什么允许这种差异以及我应该使用哪种形式?
I want to have a static function which I declare in my .c file before defining it:
//file a.c version 1
static int foo();
...
static int foo()
{
...
}
However, it seems that I can leave the static
keyword out of the function definition and I get no compiler warnings... e.g.
//file a.c version 2
static int foo();
...
int foo()
{
...
}
Am I correct in assuming these two forms are exactly the same?
If so, why is this discrepancy allowed and which form should I use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是 7.1.1/6
另请参见 7.1.1/7 的示例
Yes 7.1.1/6
See also the examples of 7.1.1/7
7.1.1/7:
7.1.1/6:(谢谢史蒂夫 - 这也是使答案清晰所需要的)
是的,这两个是一样的。
然而这是无效的:
7.1.1/7:
7.1.1/6: (Thanks Steve - this is also needed for the answer to be clear)
Yes, those two are the same.
This however is invalid:
static - 在这种情况下 - 仅影响作用域,当您将函数声明为静态时,它具有文件作用域。因此,您可以通过尝试从其他来源访问该函数来轻松检查它是否相同。
这样我们就避免了有关编译器语言等的讨论。
static - in this context - only affects the scope, when you declare a function static it has file scope. So you can easily check if it is the same by trying to access the function from another source.
that way we avoid the discussions about compiler language etc.
static 属性更改编译单元的可见性。这允许在不同的文件中出于不同的目的使用相同的名称。您应该只使用一次 static 。如果你有原型,你必须在这里做。
当您要求使用
C++
时,您不应使用静态名称空间,而应使用匿名名称空间来使符号对编译单元私有:The static attribute changes the visibility to the compilation unit. This allows to use the same name in different files for different purposes. You should use the static only once. If you have a prototype, you must do here.
When you are asking for
C++
you should not use static but anonymous namespace to make the symbold private for the compilation unit:顺便说一句,C++ 提供了一个优于
static
的替代方案。您还可以在此处使用未命名命名空间示例,
请参阅这些:
未命名命名空间相对于静态的优越性?< /a>
为什么未命名命名空间是静态命名空间的“高级”替代品?< /a>
As a sidenote, C++ provides a superior alternative to
static
. You can also use unnamed namespace hereExample,
See these:
Superiority of unnamed namespace over static?
Why an unnamed namespace is a "superior" alternative to static?