#include "MyStack.h"
#include <iostream>
usingnamespace std;
int main() {
MyStack<int> intStack(3);
int intValue;
return 0;
}
and I'm getting the following linker error:
1 2 3 4 5
$ g++ -o MyStack Main.cpp MyStack.cpp
/tmp/ccnksMQn.o: In function `main':
Main.cpp:(.text+0x16): undefined reference to `MyStack<int>::MyStack(int)'
Main.cpp:(.text+0x27): undefined reference to `MyStack<int>::~MyStack()'
collect2: ld returned 1 exit status
You can rename MyStack.cpp to have an extension that the compiler won't compile automatically and #include it at the end of the header if you want to keep it in another file
Let me and try and explain the reason this happens:
The compiler only generates code for template classes/functions when they are called explicitly. So when you try to compile your MyStack.cpp file, the compiler doesn't see any calls to the functions so it simply ignores the definitions and generates an empty object file.
When you try to link that object file with your main.cpp file, the function definitions were not compiled so the linker cannot link the calls to function code. Hence the undefined reference errors from the linker.
This is why the definitions for template code must be in the header files.