I am a newbie to C/C++ programming. Previously I have worked in Java, cobol, etc.
I have a program (List.h/List.cpp) that I intend to use later as a library program. I have compiled and tested this program with the "main" function inside the List.cpp file, it compiles and runs ok. The problem is that when I separate the "main" function and put it in a new file called main.cpp, I start getting "undefined reference" compilation errors.
I have tried using "friend" and "extern" in a main.h file but I am unable to get it working with it. Any insight into what I am doing wrong is more than welcome. I have edited out the unnecessary code.
Compilation Errors
username@username-virtual-machine:~/Source/CppMine$ make
g++ -Wall -std=c++11 -c -g List.cpp -o List.o
g++ -Wall -std=c++11 -c -g main.cpp -o main.o
g++ -Wall -std=c++11 -g List.o main.o -o main
main.o: In function `main':
/home/username/Source/CppMine/main.cpp:19: undefined reference to `List<int>::List()'
.....
File "List.h"
#ifndef H_List
#define H_List
//Definition of the node
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *next;
};
template <class Type>
class List
{
public:
List();
~List();
int count;
nodeType<Type>* first;
};
#endif
File "List.cpp"
#include <iostream>
#include "List.h"
using namespace std;
template <class Type>
List<Type>::List() //default constructor
{
count=0;
first=NULL;
}
template <class Type>
List<Type>::~List( void )
{
nodeType<Type>* current=first;
first=NULL;
nodeType<Type>* link=NULL;
while ((count>0) & (current!=NULL))
{
link = current->next;
delete current;
current=link;
link=NULL;
count--;
}
}
File "main.cpp"
#include <iostream>
#include "List.h"
using namespace std;
int main(int argc, char** argv) {
cout << "\t\tC++ Data Structures" << endl;
cout << "\t\t===================" << endl << endl;
cout << "** About to test NodeLinked for Integers..." << endl;
List<int>* myint0 = new List<int>;
delete myint0;
cout << "** About to test NodeLinked for Chars...." << endl;
List<char>* mychars = new List<char>;
delete mychars;
}
Aucun commentaire:
Enregistrer un commentaire