静态函数的优点是什么?
下面的声明:
static int *foo();
将 foo
声明为静态函数,返回指向 int
的指针。
将函数声明为 static 的目的是什么?
The declaration below:
static int *foo();
declares foo
as a static function returning a pointer to an int
.
What's the purpose of declaring a function as static ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该函数的名称在声明它的翻译单元(源文件)之外不可见,并且不会与另一个源文件中的另一个函数
foo
冲突。一般来说,函数可能应该被声明为
静态
,除非您有特定需要从另一个源文件调用它。(请注意,只有名称不可见。仍然可以通过指针从程序中的任何位置调用它。)
The function's name isn't visible outside the translation unit (source file) in which it's declared, and won't conflict with another function
foo
in another source file.In general, functions should probably be declared
static
unless you have a specific need to call it from another source file.(Note that it's only the name that's not visible. It can still be called from anywhere in the program via a pointer.)
它可以防止其他翻译单元(.c 文件)看到该函数。保持物品干净整洁。没有
static
的函数默认是extern
(对其他模块可见)。It prevents other translation units (.c files) from seeing the function. Keeps things clean and tidy. A function without
static
isextern
by default (is visible to other modules).来自C99标准:
和
From the C99 standard:
and
将函数声明为
static
可防止其他文件访问它。换句话说,它仅对声明它的文件可见; “本地”功能。您还可以将 C 中的
static
(函数声明关键字,而不是变量)关联为面向对象语言中的private
。有关示例,请参阅此处。
Declaring a function as
static
prevents other files from accessing it. In other words, it is only visible to the file it was declared in; a "local" function.You could also relate
static
(function declaration keyword, not variable) in C asprivate
in object-oriented languages.See here for an example.
将函数或全局变量标记为
static
,一旦当前翻译单元被编译到目标文件中,链接器就看不到它。换句话说,它仅在当前翻译单元内具有内部链接。当不使用
static
或显式使用extern
存储类说明符时,该符号具有外部链接。Marking a function or a global variable as
static
makes it invisible to the linker once the current translation unit is compiled into an object file.In other words, it only has internal linkage within the current translation unit. When not using
static
or explicitly using theextern
storage class specifier, the symbol has external linkage.