为什么以及何时使用静态结构的C编程? [英] Why and when to use static structures in C programming?

查看:69
本文介绍了为什么以及何时使用静态结构的C编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在司机code我被要求修改看到静态结构声明经常。

I have seen static structure declarations quite often in a driver code I have been asked to modify.

我试图寻找的信息为何结构声明静态和这样做的动机。

I tried looking for information as to why structs are declared static and the motivation of doing so.

你们任何人都可以请帮助我理解?

Can anyone of you please help me understand this?

推荐答案

在C中的静态关键字有几个方面的影响,取决于它的应用的环境。

The static keyword in C has several effects, depending on the context it's applied to.


  • 当应用于函数内声明的变量,该变量的值将是函数调用之间preserved。

  • 当施加到一个功能外声明的变量,或者一个功能,即变量或函数的可视性限制到翻译单位​​它的声明 - 即文件本身。这种对变量的归结为一种局部可见全局变量。

  • when applied to a variable declared inside a function, the value of that variable will be preserved between function calls.
  • when applied to a variable declared outside a function, or to a function, the visibility of that variable or function is limited to the "translation unit" it's declared in - ie the file itself. For variables this boils down to a kind of "locally visible global variable".

这两种用法是pretty常见于相对较低的水平code一样的驱动程序。

Both usages are pretty common in relatively low-level code like drivers.

前者和后者时,适用于变量,允许功能保持呼叫之间的状态的概念,这是非常有用的,但是这也可能导致各种讨厌的问题正在使用的code时在它被同时使用,无论是由多个线程或多个呼叫者的任何上下文。如果你不能保证code将严格地按顺序由一个用户之称,你可以通过一种背景结构即是由每次通话主叫方保留。

The former, and the latter when applied to variables, allow functions to retain a notion of state between calls, which can be very useful, but this can also cause all kinds of nasty problems when the code is being used in any context where it is being used concurrently, either by multiple threads or by multiple callers. If you cannot guarantee that the code will strictly be called in sequence by one "user", you can pass a kind of "context" structure that's being maintained by the caller on each call.

后者适用于功能,允许程序员使函数从模块之外无形的,它的可以有所加快一些编译器对于某些架构,因为编译器知道它doesn'不用为了使现有的模块外部变量/功能 - 允许内联例如功能。

The latter, applied to functions, allows a programmer to make the function invisible from outside of the module, and it MAY be somewhat faster with some compilers for certain architectures because the compiler knows it doesn't have to make the variable/function available outside the module - allowing the function to be inlined for example.

这篇关于为什么以及何时使用静态结构的C编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆