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