0

Recently my class started to dig deeper into working with generics and templates for Java. Since I'm still learning C++, I thought it would be a nice learning experience to translate the Java file.

But for some reason whenever I compile the C++ program, it gives me this error:

gabriel@desktop:/media/gabriel/main/repositories/CPP Sandbox/nodes$ g++ main.cpp node.cpp -o main
/usr/bin/ld: /tmp/ccqvlp1s.o: in function `main':
main.cpp:(.text+0x33): undefined reference to `Node<int>::Node(int)'
/usr/bin/ld: main.cpp:(.text+0x43): undefined reference to `Node<Node<int>*>::Node(Node<int>*)'
/usr/bin/ld: main.cpp:(.text+0x63): undefined reference to `Node<char const*>::Node(char const*)'
/usr/bin/ld: main.cpp:(.text+0x73): undefined reference to `Node<Node<char const*>*>::Node(Node<char const*>*)'
/usr/bin/ld: main.cpp:(.text+0x98): undefined reference to `Node<double>::Node(double)'
/usr/bin/ld: main.cpp:(.text+0xa8): undefined reference to `Node<Node<double>*>::Node(Node<double>*)'
collect2: error: ld returned 1 exit status

I'm not too sure on why it's giving me an undefined reference, but if someone could point me to the right direction that would be great.

node.h

#pragma once

#include <iostream>

template <typename T>
class Node {

    private:
        T data;
        Node *next_node;

    public:
        Node(T data);
        T get_data();
        void set_next_node(Node next);
        Node get_next_node(); 

};

node.cpp

#include "node.h"

template <typename T>

Node<T>::Node(T data) {
    this->data = data;
}

main.cpp

#include "node.h"

int main() {

    Node numb = new Node(7);
    Node str = new Node("foobar");
    Node dbl = new Node(7.5);

    return 0;
}
Gabriel Gavrilov
  • 337
  • 3
  • 11
  • 1
    You will do yourself a huge, huge favor if you completely forget everything you know about Java while learning C++. This is a very common pitfall. C++ is not Java, but its syntax is very often very similar's to Java's, and one gets into a rabbit hole believing that just because something in C++ looks like something in Java it must work the same way. It will not. C++'s templates are entirely different from Java's in multiple, fundamental ways. – Sam Varshavchik Feb 22 '23 at 01:46

0 Answers0