Reputation: 197
I am developing a common struct of {int,short,double} multi-dimension array with template in C++.
template <typename T>
struct Array {
T *x;
int size;
int nDims;
int N[ARRAYMAXNDIMS];
};
I have no problem in declaration. However, the problem occurs when I use it in function call. Please help me to correct the errors. I attach here the source code and compile error.
Thanks alot and waiting for your reply.
//============================================================================
// parse file parameter to memory
#include <cmath>
#include <cstdio>
#include <string>
#include <cstdlib>
#define ARRAYMAXNDIMS 4
using namespace std;
// multi-dimensional integer array with at most 4 dimensions
template <typename T>
struct Array {
T *x;
int size;
int nDims;
int N[ARRAYMAXNDIMS];
};
template <typename T> Array<T> reduceArrayDimension(Array<T> *a);
int main()
{
Array<int> num;
num.nDims = 4;
num.size = 16;
num.N[0] = 2; num.N[1] = 2; num.N[2] = 2; num.N[3] = 2;
num.x = (int *)calloc(num.size,sizeof(int));
for (int i=0;i < num.size; i++) {
num.x[i] = i;
};
Array<int> b = reduceArrayDimension(&num);
return 0;
}
template <typename T> Array<T> reduceArrayDim(Array<T> *a) {
// reduce 4D-array to 3D-array: [0,1,2,3] -> [0,1,2]
// B[i,j,k] = sum (A[i,j,k,l]) for all index l
Array<T> b;
b.nDims = 3;
int ax1 = a->N[0], ax2 = a->N[1], ax3 = a->N[2], ax4 = a->N[3];
b.N[0] = ax1; b.N[1] = ax2; b.N[2] = ax3; b.N[3] = 1;
b.size = ax1*ax2*ax3;
b.x = (T *)calloc(b.size,sizeof(T));
int sum = 0;
for (int i = 0; i < ax1; i++)
for (int j = 0; j < ax2; j++)
for (int k = 0; k < ax3; k++) {
sum = 0;
for (int l = 0; l < ax4; l++)
sum += a->x[i + j*ax1 + k*ax1*ax2 + l*ax1*ax2*ax3];
b.x[i + j*ax1 + k*ax1*ax2] = sum; // sum over dimension 4
}
return b;
}
error log:
$ g++ main1.cpp
/tmp/ccFwJ3tA.o: In function `main':
main1.cpp:(.text+0xba): undefined reference to `Array<int> reduceArrayDimension<int>(Array<int>*)'
collect2: error: ld returned 1 exit status
Upvotes: 0
Views: 92
Reputation: 55897
Declaration reduceArrayDimension
Definition reduceArrayDim
So, there is no definition of reduceArrayDimension
and that's why there is undefined reference here.
Upvotes: 2