First of all, let me show you what have I done so far. I have 3 files.
MemoryM.h
MemoryM.cpp
And my main.cpp file
When I compile the program, it shows me this error:
The strange thing is that if I take the definitions and paste them into the main.cpp file, the program will compile fine. Why does this happen? I had wrote the same functions as normal functions (not as templates) and they were compiling just fine. When I converted them to templates they have definitions errors. Why is that?
I am using XCode 2.4
MemoryM.h
Code:
#ifndef MEMORYM_H
#define MEMORYM_H
template<class T> T** allocate2DMemory(T **p, unsigned int xSize, unsigned int ySize);
template<class T> void dealloc2Dmemory(T **p, unsigned int xSize);
template<class T> T** realloc2Dmemory(T **p, unsigned int currentXSize, unsigned int newXSize, unsigned int newYSize);
#endif
MemoryM.cpp
Code:
#include "MemoryM.h"
/*This will allocate memory for a 2D array. The array will be created outside the function, and will be
passed as a parameter inside this function.
*/
template<class T>
T** allocate2DMemory(T **p, unsigned int xSize, unsigned int ySize){
p = new T* [xSize];
for (int i=0; i<xSize; i++) {
p[i] = new T [ySize];
}
return p;
}
/*This will deallocate the memory taken by a 2D dynamic arrays
It only needs the xSize of the array, and will delete every element
in each row of xSize*/
template<class T>
void dealloc2Dmemory(T **p, unsigned int xSize){
for (int i=0; i<xSize; i++) {
delete p[i];
}
delete [] p;
}
/*This will delete the memory taken by a 2D array and will reallocate the
array with empty memory.*/
template<class T>
T** realloc2Dmemory(char **p, unsigned int currentXSize, unsigned int newXSize, unsigned int newYSize){
for (int i=0; i<currentXSize; i++) {
delete p[i];
}
delete [] p;
p = new T* [newXSize];
for (int i=0; i<newXSize; i++) {
p[i] = new T [newYSize];
}
return p;
}
And my main.cpp file
Code:
#include <iostream>
#include <cmath>
#include "MemoryM.h"
int main (int argc, char * const argv[]){
int** t = allocate2DMemory<int>(t,100,100);
return 0;
}
When I compile the program, it shows me this error:
Code:
Tool:0: collect2: ld returned 1 exit status
Tool:0: int** allocate2DMemory<int>(int**, unsigned int, unsigned int)
Tool:0: Undefined symbols:
I am using XCode 2.4