0

Hi I got a problem with including header files with Visual Studio. The code is here:

Graph.h

#pragma once

#include <iostream>

template<typename T>
class Graph
{
public:
    Graph(int s);
    void print_graph() const;
protected:
    T** graph;
    int size;
};

Graph.cpp


#include "Graph.h"


template<typename T>
Graph<T>::Graph(int s)
{
    size = s;

    // create 2D array 
    graph = new T * [size];
    for (int i = 0; i < size; i++)
    {
        graph[i] = new T[size];
    }
}

template<typename T>
void Graph<T>::print_graph() const
{
    // print the bool matrix
    std::cout << "Graph: \n";
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
            std::cout << graph[i][j] << " ";
        std::cout << std::endl;
    }
}

main cpp

#include <iostream>
#include "Graph.h"


int main()
{
     Graph<int> g(10);
     g.print_graph();

    return 0;
}
  1. I always get error messages like, Error LNK2019 unresolved external symbol "public: __cdecl Graph::Graph(int)" (??0?$Graph@H@@QEAA@H@Z) referenced in function main.
  2. If I put everything in only one single main file (no need to include at all), everything works.
  3. But surprisingly, if I change #include "Graph.h" to #include "Graph.cpp", the program compiles. Thanks very much for your help!
Ethan
  • 161
  • 2
  • 9

1 Answers1

1

The problem is you can't do the normal .h file / .cpp file split with a class template.

This is just the way templates are. In order for the compiler to be able to instantiate a template it needs to be able to "see" the whole thing, meaning the definition not just the declaration, and further a file like your "graph.cpp" can't really be compiled into an object file. Templates are not real class definitions; they are like class definition instructions that turn it into "real" classes when they are instantiated with types.

In any case, you want to just put your whole Graph definition in the .h file and put an include guard in there so it doesnt get included multiple times.

jwezorek
  • 8,592
  • 1
  • 29
  • 46