我正在使用 @Martin 提出的解决方案 用 C++ 进行 csv 解析,因为我试图避免在我当前的项目中使用像 boost 这样的库。我已将他的实现放在“csv.h”标头中,并尝试将其包含在其他一些文件中。 构建项目时,我不断收到以下错误
操作符的多重定义>>(std::basic_istream>&, CSVRow&)
当我尝试 - 我假设发生这种情况是因为 operator>>
的重新定义与原始定义冲突。怎样才能让这两个人玩得愉快呢?谢谢。
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.
发布评论
评论(4)
很可能您在多个编译单元(即 cpp 文件)中包含相同的运算符,因此您将生成相同的代码,链接器会查看所有 .obj 文件以将它们放在一起并看到多个文件。
你有 3 个选择:
运算符仅对文件可见
它在。
删除该功能并插入
使用时的代码。
标题和正文中的原型
在它自己的 cpp 文件中。
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:
the operator visible only to the file
it was in.
rid of the function and inserts the
code at the point of use.
prototype in the header and the body
in its own cpp file.
这就是问题所在。请将其放入
csv.cpp
文件中。 :-)That is the problem. Please place it in
csv.cpp
file. :-)将其标记为内联。
Mark it as inline.
更好的是,为了可以将代码与库代码分开,您可以在项目中创建一个包含 C++ 文件及其标头的文件夹。然后,您可以在 Makefile/Makefile.am/CMakeLists 中创建一个静态存档 (
.a
),完成后您可以将其链接到主程序。这样就更清楚地表明代码是独立的,并且是一个可重用的组件,并不真正依赖于其他任何东西(如果您选择遵循这种模式,文件夹层次结构可以发挥作用)。
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).