在头文件中具有全局函数定义,并避免重复的符号链接错误 [英] Have global function definition in header file, and avoid duplicated symbol linkage error
问题描述
我在头文件中有以下代码。
I have the following code in a header only file.
#pragma once
class error_code {
public:
unsigned __int64 hi;
unsigned __int64 lo;
};
std::ostream& operator<< (std::ostream& o, const error_code& e) {
return o << "[" << e.hi << "," << e.lo << "]";
}
我得到链接错误,当项目中有2个cpp包含此标题文件
I get linkage error, when there are 2 cpp in the project include this header file.
错误LNK2005:class error_code
__cdecl operator |(class error_code const&,class ViTrox :: error_code const
&)(?? U @@ YA?AVerror_code @ 0 @ ABV10 @ 0 @ Z)
已在xxx.obj中定义
error LNK2005: "class error_code __cdecl operator|(class error_code const &,class ViTrox::error_code const &)" (??U@@YA?AVerror_code@0@ABV10@0@Z) already defined in xxx.obj
我知道我可以解决这个问题,如果我把操作符<
的定义移动到cpp文件或DLL文件。
I know I can resolve this problem, if I move the definition of operator<<
to a cpp file, or to a DLL file.
但是,我只想将它们放在 SINGLE 头文件中。有什么技术可以实现吗?或者必须将定义分隔到另一个文件?
However, I just would like to have them in a SINGLE header file. Is there any technique to achieve so? Or must I separate the definition to another file?
推荐答案
使用 inline
关键字。
inline std::ostream& operator<< (std::ostream& o, const error_code& e) {
return o << "[" << e.hi << "," << e.lo << "]";
}
这篇关于在头文件中具有全局函数定义,并避免重复的符号链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!