c - C中 `inline`关键字有什么用?

标签 c inline c99

我在 stackoverflow 中阅读了几个关于 inline in C 的问题,但仍然不清楚。

  1. static inline void f(void) {}static void f(void) {} 没有实际区别。
  2. inline void f(void) {} 在 C 中不能像 C++ 方式那样工作。它在 C 中是如何工作的?
  3. extern inline void f(void); 究竟做了什么?

我从来没有真正在我的 C 程序中发现 inline 关键字的用法,当我在其他人的代码中看到这个关键字时,它几乎总是 static inline,在我认为这与 static 没有区别。

最佳答案

C 代码可以通过两种方式进行优化:代码大小和执行时间。

内联函数:

gcc.gnu.org说,

By declaring a function inline, you can direct GCC to make calls to that function faster. One way GCC can achieve this is to integrate that function's code into the code for its callers. This makes execution faster by eliminating the function-call overhead; in addition, if any of the actual argument values are constant, their known values may permit simplifications at compile time so that not all of the inline function's code needs to be included. The effect on code size is less predictable; object code may be larger or smaller with function inlining, depending on the particular case.

因此,它告诉编译器将该函数构建到使用它的代码中,以缩短执行时间。

如果您声明小函数,如设置/清除标志或一些重复执行的位切换,inline,它可以在时间上产生很大的性能差异,但代价是代码大小。


非静态内联和静态内联

再次引用gcc.gnu.org ,

When an inline function is not static, then the compiler must assume that there may be calls from other source files; since a global symbol can be defined only once in any program, the function must not be defined in the other source files, so the calls therein cannot be integrated. Therefore, a non-static inline function is always compiled on its own in the usual fashion.


外部内联?

再次,gcc.gnu.org , 说明一切:

If you specify both inline and extern in the function definition, then the definition is used only for inlining. In no case is the function compiled on its own, not even if you refer to its address explicitly. Such an address becomes an external reference, as if you had only declared the function, and had not defined it.

这种inline和extern的结合,几乎可以达到宏的效果。使用它的方法是将一个函数定义放在带有这些关键字的头文件中,并将定义的另一个副本(缺少 inline 和 extern)放在库文件中。头文件中的定义导致对函数的大多数调用被内联。如果该函数的任何用途仍然存在,它们将引用库中的单个副本。


总结一下:

  1. 对于 inline void f(void){}inline 定义只在当前翻译单元有效。
  2. 对于 static inline void f(void) {} 由于存储类是static,标识符具有内部链接,inline定义在其他翻译单元中是不可见的。
  3. 对于 extern inline void f(void); 由于存储类是extern,标识符具有外部链接,内联定义也提供了外部定义。

关于c - C中 `inline`关键字有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31108159/

相关文章:

c++ - c++ 内联函数的要求

c - 逐个字符地构建字符串

iphone - ARC警告: Implicit declaration of function 'DLog' is invalid in C99

c - 使用SIMD优化一维热方程

c - 了解包含自身类型指针的结构

c++ - header 实现和用于优化的内联关键字

haskell - 我是否需要为小型、导出的函数使用 INLINE/INLINABLE 编译指示,还是 GHC 会为我做这件事?

C99 - 用于傻瓜的 vscanf?

c - SIGPIPE(OSX)和断开连接的套接字?

C程序中的C++ dll