0

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?

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
Elmore
  • 256
  • 3
  • 7
  • 1
    No, your knowledge of C++ is at fault, templates can only be defined in a header file. See the linked duplicate for an explanation. – john Jun 29 '22 at 12:34
  • 1
    Because it's a templated class, so either you need to have all methods definitions in your header, or you need to explicitly instantiate template instances in cpp. – pptaszni Jun 29 '22 at 12:34
  • Ha. Imagine that. Makes sense tbf. – Elmore Jun 29 '22 at 12:36
  • Sadly template recipe must be available in translation unit where it is used. This means that implementation of template it must be in header file. There are expeditions when template is manually explicitly instantiated for specific types. – Marek R Jun 29 '22 at 12:37
  • 2
    For future interactions with StackOverflow, please refrain from using expletives. It's not welcome here. – Yksisarvinen Jun 29 '22 at 12:37

0 Answers0