c – 对内联函数有不同的定义是否是一个未定义的行为?

最小代码
// --------inline.h--------
struct X { 
  static inline void foo ();
};   
#ifdef YES
inline void X::foo () { cout << "YES\n"; }
#else
inline void X::foo () { cout << "NO\n"; }
#endif

// --------file1.cpp--------
#define YES    // <---- 
#include"inline.h"
void fun1 ()
{
  X::foo();
}

// --------file2.cpp--------
#include"inline.h"
void fun2 ()
{
  X::foo();
}

如果我们调用fun1()和fun2(),那么它们将分别打印YES和NO,这意味着它们是引用相同X :: foo()的不同函数体.

无论是否应该编码,我的问题是:
这是一个明确定义还是未定义的行为?

解决方法

是的是未定义的行为.

参考:

C 03标准:

7.1.2函数说明符[dcl.fct.spec]
第4段:

An inline function shall be defined in every translation unit in which it is used and shall have exactly the same deFinition in every case (3.2). [Note: a call to the inline function may be encountered before its deFinition appears in the translation unit. ] If a function with external linkage is declared inline in one translation unit,it shall be declared inline in all translation units in which it appears; no diagnostic is required. An
inline function with external linkage shall have the same address in all translation units. A static local variable in an extern inline function always refers to the same object. A string literal in an extern inline function is the same object in different translation units.

注意:3.2指一定义规则,其中规定:

3.2一个定义规则[basic.def.odr]
第1段:

No translation unit shall contain more than one deFinition of any variable,function,class type,enumeration type or template.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...