I am using CMake (CLion) for a class project. I have tried the following solutions but they did not work: 1, 2, 3.
I made a HeapSort class for a class project and I need to use it to sort a vector of strings (a dictionary). I create an instance of my HeapSort class in this dictionary as so:
void Dictionary::heapSort()
{
Heap<std::string> h;
stringDict = h.heapSort(stringDict);
}
I keep getting an undefined reference to the constructor and the heapSort()
function, where the class is defined as follows (heapSort()
is similar):
Heap.cpp
#include "Heap.h"
template <typename T>
Heap<T>::Heap() {}
template <typename T>
void Heap<T>::initializeMaxHeap(std::vector<T> v)
{
heap = v;
heapSize = heap.size();
}
template <typename T>
void Heap<T>::maxHeapify(int i)
{
int l = left(i);
int r = right(i);
int large;
if (l <= heapSize && heap.at(l) > heap.at(i))
large = l;
else
large = i;
if (r <= heapSize && heap.at(r) > heap.at(i))
large = r;
if (large != i)
{
std::swap(heap.at(i), heap.at(large));
maxHeapify(large);
}
}
template <typename T>
void Heap<T>::buildMaxHeap()
{
for (int i = std::floor(heap.size()/2); i > 1; i++)
maxHeapify(i);
}
template <typename T>
std::vector<T> Heap<T>::heapSort(std::vector<T> v)
{
initializeMaxHeap(v);
buildMaxHeap();
for (int i = heap.size(); i > 2; i++)
{
std::swap(heap.at(1), heap.at(i));
heapSize--;
maxHeapify(1);
}
return heap;
}
Heap.h
#ifndef PROJ3_HEAP_H
#define PROJ3_HEAP_H
#include <cmath>
#include <vector>
#include "Dictionary.h"
template <typename T>
class Heap
{
private:
std::vector<T> heap;
int heapSize;
public:
Heap();
int parent(int index) { return index/2; };
int left(int index) { return index * 2; };
int right(int index) { return index * 2 + 1; };
int getItem(int index) { return heap.at(index); };
void initializeMaxHeap(std::vector<T> v);
void maxHeapify(int i);
void buildMaxHeap();
std::vector<T> heapSort(std::vector<T> v);
};
#endif //PROJ3_HEAP_H
CMakeLists.txt
cmake_minimum_required(VERSION 3.6)
project(proj3)
set(CMAKE_CXX_STANDARD 11)
set(SOURCE_FILES main.cpp Dictionary.cpp Dictionary.h Grid.cpp Grid.h Heap.cpp Heap.h)
add_executable(proj3 ${SOURCE_FILES})
Right now, I have all my files in one folder. What should I add to the CMakeLists.txt
at this time? I have tried add_library/target_link_library
(with different orders), adding include_directories
, and I tried building each class in my directory separately the linking them to the main executable. Do I need to reorganize my directory as well?
Edits: Added Heap.cpp & Heap.h