关于Stack Overflow有很多类似的帖子,但大多数都是关于Xcode的,我无法复制他们的解决方案。我有一个 * Heap. h , Heap. cpp * 和 * main. cpp * 文件,每当我尝试用g++ main.cpp Heap.cpp
运行 * main. cpp * 时,它会给我:
叮当声:错误:链接器命令失败,退出代码为1(使用-v查看调用)
文件 * 堆. 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
文件 * 堆. 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;
}
}
文件 * 主. cpp *
#include "Heap.h"
#include <iostream>
using namespace std;
int main(){
Heap <int> h;
}
奇怪的是,我有另一个包含 * bst. h 、 bst. cpp * 和 * main. cpp * 的项目,它们运行良好,这两个项目的区别在于我实现的 * bst * 不是一个模板类。
我还看到另一个类似的帖子,提到了一些关于更改位码设置的内容,但我可以从哪里访问呢?
我运行的是Xcode 7.1,苹果LLVM版本7.0.0(clang-700.1.76)。
目标:x86_64-苹果-达尔文14.5.0
螺纹型号:波斯
1条答案
按热度按时间ig9co6j11#
在
Heap.cpp
编译过程中,你不需要示例化Heap<int>
,因此编译器不会为Heap.o
生成任何代码。如果这样做,您可以看到以下内容:
它告诉你那里什么都没有。
这是C++编译器的一个典型行为-没有模板被转换成代码,除非有它的示例化。
快速解决方案包括
1.将所有Heap.cpp代码移到
Heap.h
的模板类声明中1.在示例化
Heap<int>
的Heap.cpp
中创建伪函数