c++ - 无法链接 C++ 代码

标签 c++ linker

我在同一目录下有以下三个文件:

citysim.cpp

#include "utils.h"
using namespace std;

int main()
{
    City *c;
    c = new City();
    Graph<City *> g;
    g.addVertex(c);
}

utils.h

#include <iostream>
#include <map>
#include <vector>
using namespace std;

class City {
    public:
        City() {}
    private:
        string name;
};

template <typename Tkey>
class Graph {
    public:
        Graph() {}
        void addVertex(Tkey);
    private:
        vector<Tkey> v;
        vector< vector<int> > e;
        map<Tkey, int> key_map;
};

utils.cpp

#include "utils.h"

template <typename Tkey>
void Graph<Tkey>::addVertex(Tkey vertex)
{
    v.push_back(vertex);
}

我真的很困惑为什么下面的编译序列会产生所示的结果:

test> g++ -c citysim.cpp
test> g++ -c utils.cpp
test> g++ -o citysim citysim.o utils.o
citysim.o: In function `main':
citysim.cpp:(.text+0x4a): undefined reference to `Graph<City*>::addVertex(City*)'
collect2: ld returned 1 exit status

欢迎任何想法或见解!

最佳答案

在头文件中定义模板类的所有内容,而不是在 cpp 文件中。而不是让你的 utils.cpp 在你的头文件中有这样的一切:

template <typename Tkey>
class Graph {
public:
    Graph() {}
    void addVertex(Tkey vertex)
    {
         v.push_back(vertex);
    }
private:
    vector<Tkey> v;
    vector< vector<int> > e;
    map<Tkey, int> key_map;
};

Here是FAQ中的相关阅读...

编辑: (但是您也可以稍后像在头文件中的 cpp 中那样定义它...)

关于c++ - 无法链接 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9878680/

相关文章:

c++ - 如何在dev C++中创建头文件

c++ - vector 'no operator "[Visual Studio watch 中的 ]"matches these operands' 错误

c++ - 链接器无法识别某些#includes?

compiler-construction - 程序中的标识符会发生什么?

c - 尽管选项正确,静态链接仍不适用于 C++/CLI(未解析的外部符号)

C++ 计算不准确

c++ - 第 924 行 : Char 9: runtime error: reference binding to null pointer of type 'int' (STL_vector. h)

debugging - 调试curses.h应用程序? (AppCode)

c++ - SpiderMonkey 链接错误 : FloatingPoint. h 未找到

c++ - 在处理模板时,如何避免在函数头和函数体中两次声明相同的类型?