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

时间:2022-10-19 02:04:53

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.

链接器错误中的结果:已在someother.obj文件中定义使函数内联工作正常但我无法理解为什么函数在第一种情况下已经错误输出。

3 个解决方案

#1


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.

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

#2


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).

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

#3


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

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

#1


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.

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

#2


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).

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

#3


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

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