Innkeeper
Innkeeper

Reputation: 673

Linking error with static methods

I'm unable to figure out what's the problem here. I have a ConsoleIO class, which contains two methods:

static void OutputMessage(const std::string &message);
static void OutputMessageNoNewLine(const std::string &message);

They are defined inline in the header:

inline void ConsoleIO::OutputMessage(const std::string &message)
{
    std::cout << message << std::endl;
}

inline void OutputMessageNoNewLine(const std::string &message)
{
    std::cout << message << " ";
    std::flush(std::cout);
}

Also another class, ContentParser, with the methods:

static const bool                   StringEquals(const char *a, const char *b);
                                    template <typename T>
static const std::string            NumToString(const T num);
                                    template <typename T>
static const T                      StringToNum(const std::string &s);

Which are defined in a separate file, ContentParser.cpp.

template <typename T>
const std::string ContentParser::NumToString(const T num)
{
    std::ostringstream ss;
    ss << num;
    return ss.str();
}

I have the following code in the AdventureGame class:

ConsoleIO::OutputMessageNoNewLine(ContentParser::NumToString(num+1));
ConsoleIO::OutputMessage(" - " + decision.choices.at(num).text);

The strange thing is, from the above, the bottom line works fine, but the top produces an error when linking (line 65 error). The StringEquals method also works everywhere.

Here is the build log:

14:03:02 **** Incremental Build of configuration Debug for project AdventureGame ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -o AdventureGame.o "..\\AdventureGame.cpp" 
g++ "-LD:\\Program Files\\tinyxml2-master" -o AdventureGame.exe tinyxml2.o Main.o ContentParser.o AdventureGame.o -ltinyxml 
AdventureGame.o: In function `AdventureGame::ProcessDecision()':
D:\adat\eclipse\AdventureGame\Debug/../AdventureGame.cpp:65: undefined reference to `std::string const ContentParser::NumToString<unsigned int>(unsigned int)'
D:\adat\eclipse\AdventureGame\Debug/../AdventureGame.cpp:65: undefined reference to `ConsoleIO::OutputMessageNoNewLine(std::string const&)'
D:\adat\eclipse\AdventureGame\Debug/../AdventureGame.cpp:68: undefined reference to `ConsoleIO::OutputMessageNoNewLine(std::string const&)'
collect2.exe: error: ld returned 1 exit status

What am I missing?

Upvotes: 1

Views: 1061

Answers (1)

john
john

Reputation: 87944

This

inline void OutputMessageNoNewLine(const std::string &message)
{
    std::cout << message << " ";
    std::flush(std::cout);
}

should be this

inline void ConsoleIO::OutputMessageNoNewLine(const std::string &message)
{
    std::cout << message << " ";
    std::flush(std::cout);
}

Easy mistake to make.

Upvotes: 3

Related Questions