在头文件中定义非内联函数时出现链接器错误?

发布于 2024-07-26 19:57:56 字数 217 浏览 3 评论 0原文

在带防护的头文件中定义的非内联函数

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

别低头,皇冠会掉 2024-08-02 19:57:57

如果标头包含在多个源文件中,并且该函数未标记为“内联”,那么您将拥有多个定义。 包含防护仅防止同一源文件中的多个包含。

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.

夏の忆 2024-08-02 19:57:57

您违反了单一定义规则。 如果您想直接在标头中定义函数,则必须将其标记为内联——这将允许多次定义该函数。 另请注意,内联没有其他含义,特别是它不会强制编译器内联调用(与普遍的看法相反)。

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 that inline has no other meaning, particularly it doesn't force the compiler to inline calls (contrary to popular belief).

淡淡的优雅 2024-08-02 19:57:57

由于它不是内联的,因此每个翻译单元都会有自己的函数副本,从而导致函数被多次定义。

Since it is not inline, each translation unit will have its own copy of the function resulting in the function being defined multiple times.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文