Amir Rachum
Amir Rachum

Reputation: 79635

Strange Multiple Definitions Error

I have something like this in my code:

namespace A {
namespace B {

void
GetLine(std::istream& stream, std::string& line)
{
    line.clear();
    while (stream.good()) {
        std::getline(stream, line);
        boost::trim(line);
        if (not line.empty()) break;
    }
    boost::to_upper(line);
}

}
}

And I get multiple definition error whenever I call A::B::GetLine. Any Ideas why?

(The code is at work, so I will try to give out specific snippets if you need more info, but I can't just pase the entire code here).

Upvotes: 3

Views: 234

Answers (2)

Karel Petranek
Karel Petranek

Reputation: 15154

Your problem is that you probably have this code in a .h file and include it into more .cpp files. The solution is to use inline keyword to make the compiler inline it and remove the reference:

namespace A {
namespace B {

inline void
GetLine(std::istream& stream, std::string& line)
{
    line.clear();
    while (stream.good()) {
        std::getline(stream, line);
        boost::trim(line);
        if (not line.empty()) break;
    }
    boost::to_upper(line);
}

}
}

Another solution is to move the method body to a .cpp file.

Upvotes: 1

Puppy
Puppy

Reputation: 146930

You almost certainly included the code in multiple headers, rather than declaring in a header and defining in a source file. You need to declare the function inline, template it, or move the definition into a source file but leave the declaration in a header.

Upvotes: 4

Related Questions