首页 > 解决方案 > Undefined reference with inline function c++

问题描述

I have two cpp files :

F1.cpp

using namespace std;

int i;

void Modify();

int main()
{
 i=1;
 cout << "i main 1 = " << i << endl;
 Modify();
 cout << "i main 2 = " << i << endl;

 return 0;
}

F2.cpp

using namespace std;

extern int i;

inline void Modify()
{

  i=99;

  cout << "i modify = " << i << endl;

}

When I launch the executable I get this error : F1.o: In function main : F1.cpp:(.text+0x4a): undefined reference to `Modify()' collect2: error: ld returned 1 exit status

I don't understand why this is happening since the point of an inline function is that the code is copy pasted when the function is called. So when I call Modify() in my main method, I would think that it would paste the code of the Modify() function there, therefore I don't understand why there would be an undefined reference...

Please help!

标签: c++inlinelinker-errorsexternundefined-reference

解决方案


内联函数的定义应存在于使用它的每个编译单元中。

来自 C++ 17 标准(10.1.6 内联说明符)

2 带有 inline 说明符的函数声明(11.3.5、12.2.1、14.3)声明了一个内联函数。inline 说明符向实现表明,在调用点对函数体进行内联替换优于通常的函数调用机制。在调用点执行此内联替换不需要实现;但是,即使省略了此内联替换,本节中指定的内联函数的其他规则仍应遵守。

6 内联函数或变量应在使用它的每个翻译单元中定义,并且在每种情况下都应具有完全相同的定义


推荐阅读