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

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

问题描述

我经常在要求我修改的驱动程序代码中看到静态结构声明.

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

我试图寻找关于为什么 structs 被声明为静态的信息以及这样做的动机.

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 中的 static 关键字有多种效果,具体取决于它所应用的上下文.

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

  • 当应用于函数内部声明的变量时,该变量的值将在函数调用之间保留.
  • 当应用于在函数外部声明的变量或函数时,该变量或函数的可见性仅限于 "翻译单元" 它是在文件本身中声明的.对于变量,这归结为一种局部可见的全局变量".
  • 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".

这两种用法在驱动程序等相对低级的代码中都很常见.

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

前者和后者应用于变量时,允许函数在调用之间保留状态的概念,这非常有用,但是当代码在任何上下文中使用时,这也会导致各种令人讨厌的问题它被多个线程或多个调用者同时使用.如果你不能保证代码会被一个用户"严格按顺序调用,你可以传递一种由调用者在每次调用时维护的上下文"结构.

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.

后者应用于函数,允许程序员使函数从模块外部不可见,并且对于某些体系结构的某些编译器可能会更快一些,因为编译器知道它不可见'不必使变量/函数在模块外可用 - 例如允许内联函数.

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天全站免登陆