0

I have three c++ files, sort.cpp defines a bubble sort function that takes an array, the length of the array and a function that is used to do the comparison. sort.h contains the function prototype inside a namespace. main.cpp is used to test the implementation.

sort.h:

#ifndef SORT_H
#define SORT_H

namespace sort {
    template <typename T>
    void bubble(T*, int, bool (*)(T, T));
}

#endif

sort.cpp:

#include "sort.h"

template <typename T>
void sort::bubble(T *array, int length, bool (*compare)(T, T)) {
    while (length != 0) {
        int newLength {0};
        for (int i {0}; i < length - 1; ++i) {
            if (compare(array[i], array[i+1])) {
                T temp {array[i]};
                array[i] = array[i+1];
                array[i+1] = temp;
                newLength = i + 1;
            }
        }
        length = newLength;
    }
}

main.cpp:

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

bool larger(int x, int y) {
    return x > y;
}

int main() {
    int arr[] {3, 5, 1, 3, 7, 2};
    sort::bubble(arr, 6, larger);
    for(const auto e: arr)
        std::cout << e << ' ';
    std::cout << '\n';
    return 0;
}

When I compile with g++ main.cpp sort.cpp -std=c++11 I get the error

Undefined symbols for architecture x86_64:
  "void sort::bubble<int>(int*, int, bool (*)(int, int))", referenced from:
      _main in main-767bbd.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Do I get the error because the compiler doesn't know which types I'm going to use when compiling sort.cpp? So the compiler doesn't generate any function off of the template and then the linker can't find it when I use it in main.cpp?

How can I solve this issue?

pippo
  • 35
  • 6

1 Answers1

0

Don't use two files for templates, just only one: sort.hpp There is a workaround but is not recommended.

Daniel Illescas
  • 5,346
  • 3
  • 17
  • 23