When compiling, an error occurs. It is required to make a sort function with a " universal " argument.


Undefined symbols for architecture x86_64:

"void selection_sort<float>(float*, unsigned long)", referenced from: 

_main in main.o
ld: symbol (s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see> invocation)


selectionsort.hpp

 #ifndef selectionsort_hpp #define selectionsort_hpp #include <stddef.h> #include "swap.hpp" template<typename T> void selection_sort(T[], size_t); #endif /* selectionsort_hpp */ 

selectionsort.cpp

 #include "selectionsort.hpp" template<typename T> void selection_sort(T array[], size_t size) { for (size_t i = 0; i < size - 1; i++) { size_t minimal = i; for (size_t j = i + 1; j < size; j++) { if (array[minimal] > array[j]) { minimal = j; } } swap(array[minimal], array[i]); } } 

    1 answer 1

    Template functions, unlike ordinary ones, need to be fully defined in the header.

    The fact is that a template is not a function, it is only an outline for the compiler on how a function should look like with this or that type argument. Therefore, when the compiler compiles main.cpp , it sees only the header, and cannot generate code for a specific implementation of the template function for your argument type. And when he compiles selectionsort.cpp , he, moreover, cannot do this, because at this point he does not know at all what parameters the template will be compiled in other files.

    But if the entire function is located in the header, then when compiling main.cpp compiler sees the implementation of the function, and can compile it.

    • I have already read it somewhere, but I didn’t understand what to do 😬 - Niki-Timofe
    • @ Niki-Timofe: Like what? Bring the implementation of the template function to selectionsort.hpp . Delete the selectionsort.cpp file from the project completely. - VladD
    • So? - Niki-Timofe
    • @ Niki-Timofe: Yeah, I guess so. - VladD
    • And, everything, just there were two more functions, at first it seemed that nothing had changed. Thanks for the explanation. - Niki-Timofe