Global function definition in header file - how to avoid duplicated symbol linkage error

后端 未结 4 1366
执念已碎
执念已碎 2020-11-29 11:41

I have the following code in a header only file.

#pragma once

class error_code {
public:
    unsigned __int64 hi;
    unsigned __int64 lo;    
};

std::ostr         


        
相关标签:
4条回答
  • 2020-11-29 11:49

    Either make the function inline:

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

    or make it a template function:

    template<class Ch, class Tr>
    std::basic_ostream<Ch,Tr>& operator<< (std::basic_ostream<Ch,Tr>& o,
                                           const error_code& e) {
        return o << "[" << e.hi << "," << e.lo << "]";
    }
    
    0 讨论(0)
  • 2020-11-29 11:51

    Use the inline keyword.

    inline std::ostream& operator<< (std::ostream& o, const error_code& e) {
        return o << "[" << e.hi << "," << e.lo << "]";
    }
    
    0 讨论(0)
  • 2020-11-29 12:02

    You can make the function static. It specifies internal linkage, so the linker won't care if the function is already defined in other translation units.

    Or, as already mentioned, you can make it inline. It still has external linkage, but the standard allows external inline functions to have a definition in multiple translation units.

    0 讨论(0)
  • 2020-11-29 12:09

    Define this function in .cpp file (not in .h file)

    //yoursource.cpp
    #include "yourheader.h"
    
    std::ostream& operator<< (std::ostream& o, const error_code& e) {
        return o << "[" << e.hi << "," << e.lo << "]";
    }
    
    0 讨论(0)
提交回复
热议问题