Reputation: 152
I want to use an operator defined in another file and if possible, another namespace as well, here is what I have.
(operators.hpp)
#ifndef __OPERATORS__HPP__
#define __OPERATORS__HPP__
#include "proto_handler.hpp"
#include <iostream>
namespace apius {
namespace support {
namespace operators{
std::istream& operator>>(std::istream& in,
inventory::proto::item& item);
}
}
}
(operatos.cpp)
#include "operators.hpp"
namespace apius {
namespace support {
namespace operators{
std::istream& operator>>(std::istream& in,
inventory::proto::item& item){
//code here
}
}
}
}
(another_file.cpp)
#include "operators.hpp"
extern std::istream& operator>>(std::istream& in,
inventory::proto::item& item);
void test(){
inventory::proto::item new_item;
std::cin>>new_item;
}
and I get undefined reference to operator at line containing std::cin
What can I do to make this work?
Upvotes: 0
Views: 555
Reputation: 1006
Basically the linker is struggling to find such symbol because there is no one. Because of the C++ name mangling you'll get something like __ZN5apius7support9operatorsrsERNSt3__113basic_istream... in your symbol table in an object file. Notice that the namespace part is also there. But you're telling that there is such operator in a global namespace. As Adrian correctly noticed you can simply add
using namespace apius::support::operators;
Furthermore, what I prefer to do it is to declare a friend operator in a class and then you don't need any usings.
Upvotes: 2