【发布时间】:2019-10-11 09:11:05
【问题描述】:
我遇到了 GetPot (http://getpot.sourceforge.net/) 的问题,即当我多次包含它时,链接器会收到 multiple definition 错误。
这是一个 MWE:
文件main.cpp:
#include "GetPot"
int main()
{
return 0;
}
文件foo.cpp:
#include "GetPot"
void foo()
{
GetPot configurationFileParser("foobar");
double bar = configurationFileParser("bar", 0.0);
}
(所有GetPot文件,即GetPot、GetPot.hpp和GetPot.cpp,与main.cpp和foo.cpp位于同一目录中。
用g++ main.cpp foo.cpp编译,我得到:
/tmp/ccD22ma0.o: In function `GetPot::__constraint_check(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const*, bool) const':
foo.cpp:(.text+0x0): multiple definition of `GetPot::__constraint_check(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const*, bool) const'
/tmp/ccxM8JHn.o:main.cpp:(.text+0x0): first defined here
/tmp/ccD22ma0.o: In function `GetPot::__constraint_check_OR(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const**) const':
foo.cpp:(.text+0x5ca): multiple definition of `GetPot::__constraint_check_OR(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const**) const'
/tmp/ccxM8JHn.o:main.cpp:(.text+0x5ca): first defined here
/tmp/ccD22ma0.o: In function `GetPot::__constraint_check_AND(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const**) const':
foo.cpp:(.text+0x752): multiple definition of `GetPot::__constraint_check_AND(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const**) const'
/tmp/ccxM8JHn.o:main.cpp:(.text+0x752): first defined here
/tmp/ccD22ma0.o: In function `GetPot::__constrain_check_EQUAL_STRING(char const*, char const**) const':
foo.cpp:(.text+0x692): multiple definition of `GetPot::__constrain_check_EQUAL_STRING(char const*, char const**) const'
/tmp/ccxM8JHn.o:main.cpp:(.text+0x692): first defined here
/tmp/ccD22ma0.o: In function `GetPot::__constraint_check_PRIMARY(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const**) const':
foo.cpp:(.text+0x81e): multiple definition of `GetPot::__constraint_check_PRIMARY(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char const**) const'
/tmp/ccxM8JHn.o:main.cpp:(.text+0x81e): first defined here
collect2: error: ld returned 1 exit status
(ins)mattia@endor:getpot-c++$
另一方面,将GetPot.cpp 编译成目标文件GetPot.o,然后在我的源文件中简单地包含GetPot.hpp 也不起作用,因为GetPot::operator() 仅在GetPot.cpp 中声明,因此出现错误:
/tmp/ccSIAz1V.o: In function `foo()':
foo.cpp:(.text+0x106): undefined reference to `double GetPot::operator()<double>(StringOrCharP, double) const'
collect2: error: ld returned 1 exit status
(ins)mattia@endor:getpot-c++$
无论如何,这整个问题都让我感到困惑,因为GetPot.hpp 和GetPot.cpp 都包含保护,所以一开始就不应该出现多个定义。
我做错了什么?真的没有办法在文件集合中多次包含 GetPot(特别是,例如,在编写库时)?
非常感谢
马蒂亚
【问题讨论】:
标签: c++ multiple-definition-error