即使已声明符号,架构x86_64的符号仍未定义

时间:2019-02-21 07:24:53

标签: c++

编辑1:这个问题以重复形式结束。尽管建议的重复What is an undefined reference/unresolved external symbol error and how do I fix it?以一般且非常全面的方式解决了此类“未定义符号错误”的可能原因,但并未解决我所处情况的确切原因。尽管有可能根据链接的文章中提供的信息来推理我的问题,但这样做超出了我的能力,我将需要进一步的帮助。由于这些原因,我认为对待这是一个重复的问题是不正确的。

编辑2:阅读有关针对所有模板函数放入头文件中的Kerndog73的评论,以下问题Why can templates only be implemented in the header file?的以下可接受答案回答了我的问题。

我正在实现基于邻接集的图形,并且遇到了以下编译器错误:

Undefined symbols for architecture x86_64:

"Vertex<int, int>::addEdge(Edge<int>)", referenced from:
      HashGraph<int, int>::addEdge(int, int) in hash-graph-test-99739e.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

而且我无法弄清楚为什么Vertex<int, int>::addEdge(Edge<int>)不确定。

以下是我认为与该错误有关的代码:

hash-graph.cpp

/**
 * Adds a non-existent, directed, edge from a "tail vertex" to a 
 * "head vertex" by modifying the adjacency set of the "tail vertex".
 * If the passed in edge already exists, the method instead returns
 * false.
 * 
 * @param   tail  the vertex at which the edge starts
 * @param   head  the vertex at which the edge ends
 * @return  false if edge already exists, else true
*/ 
template <class K, class V>
bool HashGraph<K, V>::addEdge(K tail, K head)
{
   Vertex<K, V> vTail = getVertex(tail);
   Edge<K> edge(head);
   return vTail.addEdge(edge);
}

template <class K, class V>
Vertex<K, V> HashGraph<K, V>::getVertex(K key)
{
   auto searchResult = graph.find(key);
   if (searchResult != graph.end())
      return searchResult->second;
   throw "Vertex not found.";
}

edge.hpp

template <class K>
class Edge
{
   private:
      static const int NO_COST = -1;
      K head;
      double cost;

   public:
      Edge(K head);
      Edge(K head, double cost);

      K getHead() const {return head;}
      double getCost() const {return cost;}

      bool operator==(const Edge<K> &other) const
      {
         return (head == other.head && cost == other.cost);
      }
};

template <class K>
Edge<K>::Edge(K head)
{
   this->head = head;
   cost = NO_COST;
}

vertex.hpp

template <class K, class V>
class Vertex
{
    private:
        K key;
        V value;
        std::unordered_set<Edge<K>> adjacencySet;

    public:
        Vertex(K key, V value);
        K getKey() const {return key;} // TODO: what does const do here exaclty>
        V getValue() const {return value;}
        bool addEdge(Edge<K> edge);

        // TODO: what does const do here exactly
        bool operator==(const Vertex<K, V> &anotherVertex) const
        {
            return key == anotherVertex.key;
        }
};

vertex.cpp

template <class K, class V>
bool Vertex<K, V>::addEdge(Edge<K> edge)
{
   if (adjacencySet.find(edge) != adjacencySet.end())
   {
      adjacencySet.insert(edge);
      return true;
   }
   return false;
}

请注意,各种文件中存在的许多代码已被省略。就我个人而言,我对getVertex方法有点怀疑,但是还没有找到任何具体的方法。

有人可以帮助我理解为什么引发此错误吗?

0 个答案:

没有答案