gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:17:59 25 4
gpt4 key购买 nike

假设 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com