在头文件中定义非内联函数时出现链接器错误?
在带防护的头文件中定义的非内联函数
#if !defined(HEADER_RANDOM_H)
#define HEADER_RANDOM_H
void foo()
{
//something
}
#endif
会导致链接器错误:已在 someother.obj 文件中定义 使函数内联工作正常,但我无法理解为什么该函数在第一种情况下已经出错。
Non inline function defined in header file with guards
#if !defined(HEADER_RANDOM_H)
#define HEADER_RANDOM_H
void foo()
{
//something
}
#endif
Results in linker error : Already defined in someother.obj file
Making the function inline works fine but I am not able to understand why the function is already erroring out in first case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果标头包含在多个源文件中,并且该函数未标记为“内联”,那么您将拥有多个定义。 包含防护仅防止同一源文件中的多个包含。
If the header is included in more than one source file and the function is not marked as "inline" you will have more than one definition. The include guards only prevent multiple inclusions in the same source file.
您违反了单一定义规则。 如果您想直接在标头中定义函数,则必须将其标记为内联——这将允许多次定义该函数。 另请注意,内联没有其他含义,特别是它不会强制编译器内联调用(与普遍的看法相反)。
You're violating the one definition rule. If you want to define a function directly in the header, you must mark it as
inline
-- that will allow the function to be defined multiple times. Also note thatinline
has no other meaning, particularly it doesn't force the compiler to inline calls (contrary to popular belief).由于它不是内联的,因此每个翻译单元都会有自己的函数副本,从而导致函数被多次定义。
Since it is not inline, each translation unit will have its own copy of the function resulting in the function being defined multiple times.