So, I have a fair bit of experience in C, but not that much in C++, and now I'm in the process of learning. I can't get a simple project to compile (or more precisely to link) - and I suspect the steaming pile of shit called CMake is at fault. My simplified example:
I have the following files:
./main.cpp
./newclass/newclass.h
./newclass/newclass.cpp
./CMakeLists.txt.
Their content is as follows:
main.cpp
#include <iostream>
#include "newclass/newclass.h"
int main() {
std::cout << "Hello, World!" << std::endl;
newclass<int>cls(123);
std::cout << "\ncls sz:" << cls.size() << "\n";
return 0;
}
newclass.h
#ifndef SUREFIRE2_NEWCLASS_H
#define SUREFIRE2_NEWCLASS_H
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <cstdio>
template <typename T>
class newclass {
public:
explicit newclass(size_t size);
~newclass() = default;
size_t size();
private:
size_t sz = 0;
};
#endif //SUREFIRE2_NEWCLASS_H
newclass.cpp
#include "newclass.h"
template <typename T>
newclass<T>::newclass(size_t size) {
this->sz = size;
}
template<typename T>
size_t newclass<T>::size() {
return this->sz;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.22)
project(tstproject)
set(CMAKE_CXX_STANDARD 14)
add_executable(tstproject
main.cpp
newclass/newclass.h
newclass/newclass.cpp
)
CMake claims:
FAILED: tstproject
: && /usr/bin/c++ -g CMakeFiles/tstproject.dir/main.cpp.o CMakeFiles/tstproject.dir/newclass/newclass.cpp.o -o tstproject && :
/usr/bin/ld: CMakeFiles/tstproject.dir/main.cpp.o: in function `main':
.../main.cpp:63: undefined reference to `newclass<int>::newclass(unsigned long)'
/usr/bin/ld: .../main.cpp:65: undefined reference to `newclass<int>::size()'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
Funny thing is that if I move the function definition into the .h file, the stuff compiles fine. What is going on?