c++ - Linking error when overloading operator << -


i want overload << operator own struct saved in own .hpp file this:

#ifndef my_structs_hpp #define my_structs_hpp  #include <iostream> #include <string>  typedef struct {     std::string a;     std::string b; } info;  std::ostream &operator<<(std::ostream &o, const info &rhs) {     o << "name: " << rhs.a << "\t" << rhs.b;     return o; }  #endif 

this how main file looks like:

#include "infobuilder.hpp" #include "mystructs.hpp" #include <iostream>  // overloading operator same, here works // std::ostream &operator<<(std::ostream &o, const info &rhs) { //     o << "name: " << rhs.a << "\t" << rhs.b; //     return o; // }  int main(){     infobuilder s();      std::cout << s.getartistinfo("architects") << std::endl;      return 0; } 

compiling gives error:

cmakefiles/foo.dir/src/infobuilder.cpp.o: in function `operator<<(std::ostream&, info const&)': infobuilder.cpp:(.text+0x159): multiple definition of `operator<<(std::ostream&, info const&)' cmakefiles/foo.dir/src/main.cpp.o:main.cpp:(.text+0xa4): first defined here collect2: error: ld returned 1 exit status make[2]: *** [cmakefiles/foo.dir/build.make:126: foo] error 1 make[1]: *** [cmakefiles/makefile2:68: cmakefiles/foo.dir/all] error 2 make: *** [makefile:84: all] error 2 

commenting overloaded operator out in mystructs.hpp file , defining in main.cpp file works. why make difference using include guards? include mystructs.hpp in infobuilder.hpp.

you've got 2 options:

option 1: put implementation of function in cc file:

mystructs.hpp

#ifndef my_structs_hpp #define my_structs_hpp  #include <iostream> #include <string>  typedef struct {     std::string a;     std::string b; } info;  std::ostream &operator<<(std::ostream &o, const info &rhs);  #endif 

mystructs.cpp

#include <iostream> #include <string> #include "mystructs.hpp"  std::ostream &operator<<(std::ostream &o, const info &rhs) {     o << "name: " << rhs.a << "\t" << rhs.b;     return o; } 

option 2: mark function static

mystructs.hpp

#ifndef my_structs_hpp #define my_structs_hpp  #include <iostream> #include <string>  typedef struct {     std::string a;     std::string b; } info;  static std::ostream &operator<<(std::ostream &o, const info &rhs) {     o << "name: " << rhs.a << "\t" << rhs.b;     return o; }  #endif 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -