c++ - 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++ 17 标准(10.1.6 内联说明符)
2 带有 inline 说明符的函数声明(11.3.5、12.2.1、14.3)声明了一个内联函数。inline 说明符向实现表明,在调用点对函数体进行内联替换优于通常的函数调用机制。在调用点执行此内联替换不需要实现;但是,即使省略了此内联替换,本节中指定的内联函数的其他规则仍应遵守。
和
6 内联函数或变量应在使用它的每个翻译单元中定义,并且在每种情况下都应具有完全相同的定义
推荐阅读
- python - 从数据框中删除列中的一些特定关键字并将其保存到 json
- continuous-integration - JFrog Xray 3.0 的计划是什么?
- apache-spark - 如何查找 Spark 集群的工作人员信息?
- f# - 为什么 F# 可区分联合无法使其 TypeConverter 受到 JSON.NET 的尊重,而其他类型却可以?
- javascript - 如何设置位置固定水平和粘性垂直
- github - GitHub 是否允许您创建多个 (2) 个人帐户?
- reactjs - amp 页面在 nextjs 项目中停止工作,cdn.ampproject.org 出错,无法加载资源
- listview - Xamarin 表单:不同的项目正在调用而不是 flowlistview 中的选定项目?
- c# - 如何使用预构建事件命令行将参数传递给 T4 模板
- angular - 如何将 [] 中的值以角度传递给 API?