-1

It does not want to be compiled. Problem overview:

/usr/bin/ld: CMakeFiles/test.dir/main.cpp.o: in function `main':
/mnt/c/Users/Pasha/CLionProjects/test/main.cpp:4: undefined reference to `box<int>::box()'
/usr/bin/ld: /mnt/c/Users/Pasha/CLionProjects/test/main.cpp:4: undefined reference to `box<int>::~box()'
collect2: error: ld returned 1 exit status

I had this issue before my program looks like this. Recently it worked but something went wrong and I got that. I deleted almost everything and got it easier as much as possible I check directory and setting

main.cpp

#include "box.h"
int main() {
    box user_box;
    return 0;
}

box.cpp

#include "box.h"
template<typename Type>
box<Type>::box(){
    pp = new Type*[size_box];
    for (int i = 0; i < size_box; i++){
        pp[i] = new Type[size_box];
    }
}

template <typename T>
box<T>::~box(){
    for (int i = 0; i < size_box; i++){
        delete[] pp[i];
    }
    delete[] pp;
}

and box.h

#ifndef USER_BOX_BOX_H
#define USER_BOX_BOX_H

#define size_box 10
class box{
private:
    T** pp;
public:
    box();
    ~box();
};
#endif //USER_BOX_BOX_H

I would be glad to get help and some explanation, other projects with the concept are right and the compiler does not complain. And IF I CHANGE .H TO .CPP IT WORKS. I dont understand

Xxproner_
  • 1
  • 2
  • 2
    Where is `box::~box` defined? – Eljay Aug 14 '23 at 20:32
  • Does [this](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) answer your question? – Jesper Juhl Aug 15 '23 at 07:18
  • https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file ? – pptaszni Aug 15 '23 at 07:32
  • (0) The `box` class declaration is not templated whereas the method definitions are expecting it to be templated. How do you expect that to work? How do the two different files called `box.h` interact? (1) Don’t use raw pointers; there’s no need for them here. Also, avoid “Java style” array allocation. The member `pp` should be (a) `std::array`, (b) `std::unique_ptr` or some such. – Andrej Podzimek Aug 16 '23 at 13:06

0 Answers0