10

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 << "]";
}

I get linkage error, when there are 2 cpp in the project include this header file.

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

I know I can resolve this problem, if I move the definition of operator<< to a cpp file, or to a DLL file.

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?

1
  • The error message doesn't match your code snippet. Commented Jan 5, 2011 at 4:11

4 Answers 4

18

Use the inline keyword.

inline std::ostream& operator<< (std::ostream& o, const error_code& e) {
    return o << "[" << e.hi << "," << e.lo << "]";
}
Sign up to request clarification or add additional context in comments.

12 Comments

Not chapter and verse, but IIRC if you don't have inline it violates ODR (and if you do have inline but two or more different bodies it also violates ODR).
inline is just a hint to the compiler, it may not inline sometimes.
@Nawaz, yes for the purposes of optimization. But in this case we're leveraging it to specify linkage.
@Nawaz: No! inline is not just a hint to the compiler. This is a correct and appropriateuse of inline.
@Logan Capaldo: inline doesn't affect a function's linkage. inline functions still have external linkage by default.
|
7

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 << "]";
}

Comments

3

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.

Comments

0

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 << "]";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.