gpt4 book ai didi

c++ - 内联函数 C++ 的 undefined reference

转载 作者:行者123 更新时间:2023-12-01 22:34:16 29 4
gpt4 key购买 nike

我有两个 cpp 文件:

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;

}

当我启动可执行文件时,出现此错误:F1.o:在函数 main 中:F1.cpp:(.text+0x4a):对“Modify()”的 undefined reference 收集2:错误:ld返回1退出状态

我不明白为什么会发生这种情况,因为内联函数的要点是在调用函数时复制粘贴代码。因此,当我在主方法中调用Modify()时,我会认为它会将Modify()函数的代码粘贴到那里,因此我不明白为什么会有 undefined reference ...

请帮忙!

最佳答案

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

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

2 A function declaration (11.3.5, 12.2.1, 14.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions specified in this section shall still be respected.

6 An inline function or variable shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case

关于c++ - 内联函数 C++ 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59917550/

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