0

Im keep getting this error when compile my project, its works when remove the template , i don't really know why, hope someone can help , thanks!

arrayprocessor.h

#include <iostream>

using namespace std;

template <typename T>
void ExtractArray(T* arr, int size);

arrayprocessor.cpp

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

using namespace std;

template <typename T>

    void ExtractArray(T *a, int size)
    {
        for (int i = 0; i < size; i++)
        {
            cout << *a[i] << endl;
        }
    }

main.cpp

#include <iostream>
#include "HeaderFiles/arrayprocessor.h"

using namespace std;

int main()
{
    double arr[]{1.3, 3.5, 4.6};
    ExtractArray(arr, sizeof(arr) / sizeof(arr[0]));
    return 0;
}

the error:

Starting build...
D:/MSYS64/mingw64/bin/g++.exe -fdiagnostics-color=always -g "D:\C++ Projects/*.cpp" "D:\C++ Projects/HeaderFiles/*.cpp" "D:\C++ Projects/HeaderFiles/*.h" -o "D:\C++ Projects/bin/main"
D:/MSYS64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\WINDOW~1\AppData\Local\Temp\ccY9tEnW.o:D:\C++ Projects/main.cpp:16: undefined reference to `void ExtractArray<double>(double*, int)'
collect2.exe: error: ld returned 1 exit status

Build finished with error(s).

 *  The terminal process terminated with exit code: -1. 
 *  Terminal will be reused by tasks, press any key to close it. 
Trong Thang
  • 33
  • 1
  • 5
  • 1
    You either need the template implementation in the header file (more usual) or to use explicit template instantiation. – Avi Berger Aug 05 '22 at 05:40
  • To automatically deduce the size of the array (as opposed to specifying it explicitly in `size`), you can do `template void ExtractArray(T (&a)[N])`. `N` will then hold the size of the array. – frippe Aug 05 '22 at 05:56

0 Answers0