c++ - 跨多个文件的命名空间 "undefined reference"错误

标签 c++ reference namespaces undefined

我查看了几篇相关的帖子,但没有遇到这个错误。 当我的命名空间存在于多个文件中时,我在下面收到此 undefined reference 错误消息。如果我只编译 ConsoleTest.cpp 并将 Console.cpp 的内容转储到其中,则源代码会编译。

在此先感谢您对此问题的任何反馈。

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

控制台.h

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

namespace Console
{
    std::string getLine();

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

控制台.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;
    }
}

控制台测试.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;
}

最佳答案

模板函数需要在头文件中定义,而不仅仅是声明。编译器需要查看模板实现和模板参数来构建您在 main 中所需的特化。所以直接把定义放在header中:

namespace Console
{
    std::string getLine();

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

    }
}

关于c++ - 跨多个文件的命名空间 "undefined reference"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10135667/

相关文章:

c++ - 为什么 g++ 和 MS Visual Studio C++ 执行以下代码的方式不同?

c# - 如何访问通用存储库类中的 DbContext.Entry<TEntity> 方法 (TEntity)?

c++ - 通过保留和复制,还是通过创建和交换来复制 vector 更有效?

c# - C++ 后台代码分析器,如 C# 的 Resharper?

c++ - 我可以使用命名空间中的一些但不是全部名称,而不必为所有名称重复完整范围吗?

reference - 关于在 Go 上使用等号和 map 的说明

c++ - & 在类型后的函数参数中

c# - 如果我调用自己的类 "Vector"会引起问题吗?

php - 在类里面使用第 3 方 api 时的命名空间冲突

C++抛出异常非法