tags:

views:

61

answers:

2

Hi all, 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).

+3  A: 

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.

DeadMG
So simple... Thanks!
Amir Rachum
+1  A: 

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.

dark_charlie