C静态内联函数重定义规则

标签 c function static shadow undefined-behavior

假设 bar.h可能存在:

static inline int fun () { return 2; }

并确保 fun 始终被定义 foo.h 包含以下内容:

static inline int fun () { return 3; }

bar.h 包含定义时,以下是否会引发未定义的行为?

#include "foo.h" /* ensure there is always a definition */
#include "bar.h" /* use the bar definition if it exists */

int main () {
   /* ... */
   int x = fun ();
   /* ... */

使用 gcc (4.0.1)(旧的,但这是我目前拥有的)行为符合预期 - foo 版本在 bar 版本缺失时使用,而 bar 版本存在时使用。

最佳答案

不,这是不允许的。 fun() 的那些定义声明 fun() 具有内部链接(由于 static),C 标准中的 §6.9 说:

There shall be no more than one external definition for each identifier declared with internal linkage in a translation unit.

违反“shall”子句是未定义行为,这意味着您的程序的语义完全未定义,编译器不必发出错误消息。

关于C静态内联函数重定义规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6448276/

相关文章:

c - 在用户级线程库中实现join函数

c - string.h 中的 gcc 函数会破坏 UTF-8 字符串吗?

python 捕捉功能

java - 私有(private)最终静态属性与私有(private)最终属性

c - 使用 A Vedaldi 的 sift 实现

c - C中二叉搜索树的删除

c - 为什么不在函数内部执行printf?

c++ - 在其他函数中对结构 vector 和 vector 部分进行排序?

c++ - 初始化字符串的静态数组(C++)?

multithreading - 在多核嵌入式 Rust 中,我可以使用静态 mut 进行单向数据共享吗?