c - 没有 "inline"或 "static"的 "extern"在 C99 中有用吗?

标签 c inline c99

当我尝试构建这段代码时

inline void f() {}

int main()
{
    f();
}

使用命令行

gcc -std=c99 -o a a.c

我收到链接器错误(对 f 的 undefined reference )。如果我使用 static inlineextern inline 而不仅仅是 inline,或者如果我使用 -O 进行编译,错误就会消失>(所以函数实际上是内联的)。

这种行为似乎在 C99 标准的第 6.7.4 (6) 段中定义:

If all of the file scope declarations for a function in a translation unit include the inline function specifier without extern, then the definition in that translation unit is an inline definition. An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit. An inline definition provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.

如果我对这一切的理解是正确的,那么只有当还有一个具有相同名称的外部函数时,如上例中定义了 inline 函数的编译单元才会一致地编译,而且我不知道是否我自己的函数或外部函数被调用。

这种行为是不是很愚蠢?在 C99 中定义没有 staticextern 的函数 inline 有用吗?我错过了什么吗?

答案总结

当然,我遗漏了一些东西,而且这种行为并不愚蠢。 :)

作为Nemo explains , 思路是把函数的定义

inline void f() {}

在头文件中,只有一个声明

extern inline void f();

在对应的.c文件中。只有 extern 声明会触发生成外部可见的二进制代码。在 .c 文件中确实没有使用 inline -- 它只在标题中有用。

作为rationale of the C99 committee quoted in Jonathan's answer explicates,inline 是关于编译器优化的,它要求函数的定义在调用位置可见。这只能通过将定义放在 header 中来实现,当然, header 中的定义不能每次被编译器看到时都发出代码。但是由于编译器并没有被迫实际内联一个函数,所以外部定义必须存在于某处。

最佳答案

其实这个优秀的答案也回答了你的问题,我认为:

What does extern inline do?

想法是可以在头文件中使用“inline”,然后在.c 文件中使用“extern inline”。 “外部内联”就是您指示编译器哪个目标文件应包含(外部可见的)生成代码的方式。

[更新,详细说明]

我认为 .c 文件中的“内联”(没有“static”或“extern”)没有任何用处。但在头文件中它是有意义的,并且它需要在某些 .c 文件中相应的“extern inline”声明才能实际生成独立代码。

关于c - 没有 "inline"或 "static"的 "extern"在 C99 中有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6312597/

相关文章:

c - C 中的 math.sqrt 问题

使用 "<"或 ">"运算符比较字符串 (C)

c++ - 从内联函数调用非内联函数

html - 覆盖内联 CSS 的媒体查询

c++ - 从 C++ 提供 C99 复杂参数

c - gcc 永久更改 c 标准

C:错误嵌套的 switch/case block 出人意料地有效

C 错误 TLS 错误

javascript - 如何内联显示未定义数量的 div?

c - 创建大小为零的灵活数组成员是否合法?