0

i oeverloading [] in my "vector.h" and difine it in "vector.cpp",but the cmake linking fails and i don't know why

vector.h file

template<typename T>
class Vector             
{
protected:
    Rank _size;
    int _capacity;
    T *_elem;
public:
    Vector(){ _elem = new T[_capacity = DEFAULT_CAPACITY];  _size = 0;}
    ~Vector() { delete[] _elem; }
     
    T& operator[](Rank r);

vector.cpp file

template<typename T>
T &Vector<T>::operator[](Rank r) { return _elem[r]; }

This is how my CMakeLists.txt looks like

cmake_minimum_required(VERSION 3.21)
project(Algorithm_Test)

set(CMAKE_CXX_STANDARD 11)

add_executable(Algorithm_Test main.cpp vector.h vector.cpp)

when i put "operator[]" define in vector.h and it worked, but i still don't know why

[1/1] Linking CXX executable Algorithm_Test.exe FAILED: Algorithm_Test.exe cmd.exe /C "cd . && C:\PROGRA~1\JETBRA~1\CLION2~1.3\bin\mingw\bin\G__~1.EXE -g CMakeFiles/Algorithm_Test.dir/main.cpp.obj CMakeFiles/Algorithm_Test.dir/vector.cpp.obj -o Algorithm_Test.exe -Wl,--out-implib,libAlgorithm_Test.dll.a -Wl,--major-image-version,0,--minor-image-version,0 -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ." C:\Program Files\JetBrains\CLion 2021.3.3\bin\mingw\bin/ld.exe: CMakeFiles/Algorithm_Test.dir/main.cpp.obj:E:/1_Cpp_package/Clion Data Structure and Algorithm/Algorithm_Test/main.cpp:64: undefined reference to `Vector::operator' collect2.exe: error: ld returned 1 exit status ninja: build stopped: subcommand failed.

What am i doing wrong

  • If you put the implementation of the `operator[]` in a `.cpp` file, then you need to *explicitly* instantiate the template for each type that you care about in that `.cpp` file. Which is why the template function implementations are usually provided in the header file, so the compiler can implicitly generate them when instantiated. Those instantiated templates have *weak linkage*, so you only get one in your executable. – Eljay Apr 18 '22 at 16:42

0 Answers0