5

I'm using the proposed solution by @Martin for csv parsing with C++, as I'm trying to avoid using libraries like boost and such for my current project. I've placed his implementation in a "csv.h" header and am trying to include it with some other files. I keep getting the following error

multiple definition of operator>>(std::basic_istream<char, std::char_traits<char> >&, CSVRow&)

when I try to build the project - I'm assuming this happens because the redefinition of operator>> clashes with the original one. How can I make these two play nice? thanks.

Community
  • 1
  • 1
sa125
  • 28,121
  • 38
  • 111
  • 153

4 Answers4

9

Chances are you have the same operator included in multiple compilation units (ie cpp files) so you're getting the same code generated, the linker than looks at all the .obj files to pull them together and sees multiples.

You have 3 choices:

  • mark it as static - this will make the operator visible only to the file it was in.
  • mark it inline - this gets rid of the function and inserts the code at the point of use.
  • Put the prototype in the header and the body in its own cpp file.
gbjbaanb
  • 51,617
  • 12
  • 104
  • 148
4

I've placed his implementation in a "csv.h" header

That is the problem. Please place it in csv.cpp file. :-)

Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

Mark it as inline.

inline istream & operator>>( istream & is, CSVRow & row ) {
    // stuff
}
0

Even better, so that you can separate your code from the library-ish code, you can make a folder in your project that contains the C++ file and a header with it. Then you can, in your Makefile/Makefile.am/CMakeLists, create a static archive (.a) which you can link into your main program when done.

This way its much more clear that the code is separate and a reusable component that doesn't really depend on anything else (which is one thing a folder hierarchy can be useful for, if you choose to follow this pattern).

alternative
  • 12,703
  • 5
  • 41
  • 41