"undefined reference" error with namespace across multiple files

Posted by user1330734 on Stack Overflow See other posts from Stack Overflow or by user1330734
Published on 2012-04-13T05:25:28Z Indexed on 2012/04/13 5:28 UTC
Read the original article Hit count: 130

Filed under:
|
|
|
|

I've looked at several related posts but no luck with this error. I receive this undefined reference error message below when my namespace exists across multiple files. If I compile only ConsoleTest.cpp with contents of Console.cpp dumped into it the source compiles.

I would appreciate any feedback on this issue, thanks in advance.

g++ Console.cpp ConsoleTest.cpp  -o ConsoleTest.o -Wall

/tmp/cc8KfSLh.o: In function `getValueTest()':
 ConsoleTest.cpp:(.text+0x132): undefined reference to `void Console::getValue<unsigned int>(unsigned int&)'
collect2: ld returned 1 exit status

Console.h

#include <iostream>
#include <sstream>
#include <string>

namespace Console
{
    std::string getLine();

    template <typename T>
    void getValue(T &value);
}

Console.cpp

#include "Console.h"

using namespace std;

namespace Console
{
    string getLine()
    {
        string str;
        while (true)
        {
            cin.clear();
            if (cin.eof()) {
                break;  // handle eof (Ctrl-D) gracefully
            }

            if (cin.good()) {
                char next = cin.get();
                if (next == '\n')
                    break;
                str += next;    // add character to string
            } else {
                cin.clear(); // clear error state
                string badToken;
                cin >> badToken;
                cerr << "Bad input encountered: " << badToken << endl;
            }
        }
        return str;
    }               


    template <typename T>
    void getValue(T &value)
    {
        string inputStr = Console::getLine();
        istringstream strStream(inputStr);

        strStream >> value;
    }
}

ConsoleTest.cpp

#include "Console.h"

void getLineTest()
{
    std::string str;

    std::cout << "getLinetest" << std::endl;

    while (str != "next")
    {
        str = Console::getLine();
        std::cout << "<string>" << str << "</string>"<< std::endl;
    }
}

void getValueTest()
{
    std::cout << "getValueTest" << std::endl;
    unsigned x = 0;
    while (x != 12345)
    {
        Console::getValue(x);
        std::cout << "x: " << x << std::endl;
    }
}

int main()
{
    getLineTest();
    getValueTest();
    return 0;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about reference