clang 错误链接器命令失败

clang error linker command failed

SO 上有很多 post 类似的问题,但其中大部分属于 xcode,我无法复制他们的解决方案。我有一个 Heap.h、Heap.cpp 和 main.cpp,每当我尝试 运行 main.cpp 和 g++ main.cpp Heap.cpp 时,它都会给我:

clang: error: linker command failed with exit code 1 (use -v to see invocation)

Heap.h

#ifndef _HEAP_H_
#define _HEAP_H_

template<class T>
class Heap{
    private:
        struct Node{
            T *dist;
            T *v;

            bool operator==(const Node& a){
                return *dist == *(a -> dist);
            }

            bool operator!=(const Node& a){
                return (!(*dist == *(a -> dist)));
            }

        };

        Node *container;
        int size;
        int curSize;
        T sourceV;        

    public:
        Heap();
        Heap(int inSize, T inSourceV);

};

    #endif

Heap.cpp

#include <iostream>
#include <vector>
#include <limits>
#include "Heap.h"

using namespace std;

template<class T>
Heap<T>::Heap(){
    cout << "hello" <<endl;
}

template<class T>
Heap<T>::Heap(int inSize, T inSourceV){
    size = inSize;
    container = new Node[size];
    curSize = 0;
    sourceV = inSourceV;

    int maxVal = numeric_limits<int>::max();
    for (int i = 1; i < size; i++){
        container[i].dist = &maxVal;
        container[i].v = &maxVal;
    }
}

main.cpp

#include "Heap.h"
#include <iostream>

using namespace std;

int main(){
   Heap <int> h; 
}

奇怪的是,我有另一个包含 bst.h bst.cpp main.cpp 和 运行 的项目。这两个项目的区别在于我实现的bst不是模板化的class。

我还看到另一个类似的 post 提到了一些关于更改位码设置的内容,但我不知道从哪里访问它。有什么想法吗?

我 运行宁 xcode 7.1。 Apple LLVM 版本 7.0.0 (clang-700.1.76) 目标:x86_64-apple-darwin14.5.0 线程模型:posix

您没有在 Heap.cpp 编译中实例化 Heap<int>。因此,编译器不会为 Heap.o.

生成 any 代码

如果你这样做,你会看到这个:

nm Heap.o

它告诉你那里什么都没有。

这是 C++ 编译器的典型行为 - 除非有模板的实例化,否则不会将模板转换为代码。

快速解决方案是

  1. 将所有 Heap.cpp 代码移动到 Heap.h
  2. 的模板 class 声明中
  3. Heap.cpp 中创建一个虚拟函数来实例化 Heap<int>