头文件中的全局函数定义-如何避免重复的符号链接错误 [英] Global function definition in header file - how to avoid duplicated symbol linkage error

查看:61
本文介绍了头文件中的全局函数定义-如何避免重复的符号链接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在仅标头文件中有以下代码。

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:错误代码类
__cdecl运算符|(错误代码类const& ;,类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

如果将 operator<< 的定义移动到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?

推荐答案

使用内联

Use the inline keyword.

inline std::ostream& operator<< (std::ostream& o, const error_code& e) {
    return o << "[" << e.hi << "," << e.lo << "]";
}

这篇关于头文件中的全局函数定义-如何避免重复的符号链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆