I have a header file that looks like this:
#pragma once
//C++ Output Streams
#include <iostream>
namespace microtask
{
namespace log
{
/**
* Severity level.
*/
enum severity
{
debug,
info,
warning,
error,
critical
};
/**
* Output the severity level.
*/
std::ostream& operator<<(std::ostream& out, const severity& level);
}
}
and a source file that looks like this:
//Definitions
#include "severity.hpp"
//Namespaces
using namespace std;
using namespace microtask::log;
std::ostream& operator<<(std::ostream& out, const severity& level)
{
switch(level)
{
case debug:
out << "debug";
break;
case info:
out << "info";
break;
case warning:
out << "warning";
break;
case error:
out << "error";
break;
case critical:
out << "critical";
break;
default:
out << "unknown";
break;
}
return out;
}
that I am trying to compile into a dynamic library. Unfortunately, linking fails with this error message:
undefined reference to `microtask::log::operator<<(std::basic_ostream<char, std::char_traits<char> >&, microtask::log::severity const&)'
What am I doing wrong? I’ve checked other stackoverflow.com questions that seemed similar, but as far as I can tell, I have the format for overloading the operator correct.
In your .cpp file, don’t say
using, but instead declare the proper namespace:In fact, don’t say
usingcasually at all if you can help it. In my opinion it should be reserved for explicit base member unhiding and ADL requests.