C语言 在 C 中使用静态函数和变量的原因
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2973849/
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
Reasons to use Static functions and variables in C
提问by Gauthier
I wonder about the use of the statickeyword as scope limiting for variables in a file, in C.
我想知道在 C 中使用static关键字作为文件中变量的范围限制。
The standard way to build a C program as I see it is to:
在我看来,构建 C 程序的标准方法是:
- have a bunch of c files defining functions and variables, possibly scope limited with
static. - have a bunch of h files declaring the functions and possibly variables of the corresponding c file, for other c files to use. Private functions and variables are not published in the h file.
- every c file is compiled separately to an o file.
- all o files are linked together to an application file.
- 有一堆定义函数和变量的 c 文件,可能范围受限于
static. - 有一堆 h 文件声明相应 c 文件的函数和可能的变量,供其他 c 文件使用。私有函数和变量未在 h 文件中发布。
- 每个 c 文件都单独编译为一个 o 文件。
- 所有 o 文件都链接到一个应用程序文件。
I see two reasons for declaring a gobal as static, if the variable is not published in the h file anyway:
static如果变量未在 h 文件中发布,我看到将 gobal 声明为的两个原因:
- one is for readability. Inform future readers including myself that a variable is not accessed in any other file.
- the second is to prevent another c file from redeclaring the variable as
extern. I suppose that the linker would dislike a variable being bothexternandstatic. (I dislike the idea of a file redeclaring a variable owned by someone else asextern, is it ok practice?)
- 一是为了可读性。告知未来的读者,包括我自己,在任何其他文件中都不会访问变量。
- 第二个是防止另一个 c 文件将变量重新声明为
extern. 我想链接器会不喜欢一个变量既是extern又是static。(我不喜欢文件将其他人拥有的变量重新声明为 的想法extern,这可以实践吗?)
Any other reason?
还有什么原因吗?
Same goes for staticfunctions. If the prototype is not published in the h file, other files may not use the function anyway, so why define it staticat all?
I can see the same two reasons, but no more.
也是一样的static功能。如果原型没有发布在 h 文件中,那么其他文件无论如何都可能不会使用该函数,那为什么要定义它static呢?我可以看到相同的两个原因,但没有更多。
采纳答案by crazyscot
When you talk about informing other readers, consider the compiler itself as a reader. If a variable is declared static, that can affect the degree to which optimizations kick in.
当您谈论通知其他读者时,请将编译器本身视为读者。如果声明了一个变量static,则会影响优化的程度。
Redefining a staticvariable as externis impossible, but the compiler will (as usual) give you enough rope to hang yourself.
重新定义一个static变量extern是不可能的,但是编译器会(像往常一样)给你足够的绳子来吊死自己。
If I write static int foo;in one file and int foo;in another, they are considered different variables, despite having the same name and type - the compiler will not complain but you will probably get very confused later trying to read and/or debug the code. (If I write extern int foo;in the second case, that will fail to link unless I declare a non-static int foo;somewhere else.)
如果我static int foo;在一个文件和int foo;另一个文件中写入,它们被认为是不同的变量,尽管具有相同的名称和类型 - 编译器不会抱怨,但稍后您可能会在尝试读取和/或调试代码时感到非常困惑。(如果我extern int foo;在第二种情况下写,除非我在int foo;其他地方声明非静态,否则将无法链接。)
Global variables rarely appear in header files, but when they do they should be declared extern. If not, depending on your compiler, you risk that every source file which includes that header will declare its own copy of the variable: at best this will cause a link failure (multiply-defined symbol) and at worst several confusing cases of overshadowing.
全局变量很少出现在头文件中,但是当出现时应该声明它们extern。如果不是,则取决于您的编译器,您可能会面临包含该头文件的每个源文件都将声明其自己的变量副本的风险:充其量这将导致链接失败(多重定义的符号),最坏的情况下会导致一些令人困惑的遮蔽情况。
回答by qrdl
By declaring a variable staticon file level (staticwithin function has a different meaning) you forbid other units to access it, e.g. if you try to the variable use inside another unit (declared with extern), linker won't find this symbol.
通过static在文件级别声明一个变量(static在函数内有不同的含义),您禁止其他单元访问它,例如,如果您尝试在另一个单元内使用该变量(用 声明extern),链接器将找不到此符号。
回答by INS
回答by Adam Rosenfield
If a global variable is declared static, the compiler can sometimes make better optimizations than if it were not. Because the compiler knows that the variable cannot be accessed from other source files, it can make better deductions about what your code is doing (such as "this function does not modify this variable"), which can sometimes cause it to generate faster code. Very few compilers/linkers can make these sorts of optimizations across different translation units.
如果全局变量被声明为静态的,编译器有时可以进行比不声明更好的优化。因为编译器知道不能从其他源文件访问该变量,所以它可以更好地推断您的代码正在做什么(例如“此函数不修改此变量”),这有时会使其生成更快的代码。很少有编译器/链接器可以跨不同的翻译单元进行此类优化。
回答by gnasher729
If you declare a variable foo in file a.c without making it static, and a variable foo in file b.c without making it static, both are automatically extern which means the linker may complain if you initialise both, and assign the same memory location if it doesn't complain. Expect fun debugging your code.
如果你在文件 ac 中声明一个变量 foo 而不将其设为静态,而在文件 bc 中声明一个变量 foo 而不将其设为静态,则两者都会自动为 extern,这意味着如果你初始化两者,链接器可能会抱怨,如果没有,则分配相同的内存位置不要抱怨。期待有趣的调试您的代码。
If you write a function foo () in file a.c without making it static, and a function foo () in file b.c without making it static, the linker may complain, but if it doesn't, all calls to foo () will call the same function. Expect fun debugging your code.
如果你在文件 ac 中编写了一个函数 foo() 而不将其设为静态,并且在文件 bc 中编写了一个函数 foo() 而不将其设为静态,链接器可能会抱怨,但如果没有,所有对 foo() 的调用都会调用相同的功能。期待有趣的调试您的代码。
回答by Jake Kalstad
My favorite usage of static is being able to store methods that I wont have to Inject or create an object to use, the way I see it is, Private Static Methods are always useful, where public static you have to put some more time in thinking of what it is your doing to avoid what crazyscot defined as, getting your self too much rope and accidentally hanging ones self!
我最喜欢静态的用法是能够存储我不必注入或创建要使用的对象的方法,我认为它是,私有静态方法总是有用的,公共静态你必须花更多时间思考你正在做什么来避免疯狂斯科特定义的那样,让你自己绳索太多,不小心把自己吊死!
I like to keep a folder for Helper classes for most of my projects that mainly consist of static methods to do things quickly and efficiently on the fly, no objects needed!
我喜欢为我的大多数项目保留一个用于 Helper 类的文件夹,这些项目主要由静态方法组成,以便快速高效地执行任务,不需要对象!

