I encountered a problem where the template function defined in a separate file couldn't be found by the g++ compiler.
Case 1: the template function is defined in the same file as main() is. I can compile it with no issue.
======== code of case 1 =========
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
template<class TYPE>
void
printArray(TYPE *s, int n)
{
if (n <= 0)
return;
cout << "Array:";
for (int i = 0; i < n; i++) {
cout << " " << s[i];
}
cout << endl;
}
int main() {
int s[] = {5, 4, 7, 2, 2, 3};
int n = sizeof(s) / sizeof(s[0]);
cout << "size of s is " << n << endl;
printArray(s, n);
return 0;
}
|
=================================
Case 2: the template function is defined in a separate file. I got the following error when compiling it.
Compile command: g++ sortexp.cc help.cc
Error message:
/tmp/ccoz4qpG.o: In function `main':
sortexp.cc:(.text+0xd4): undefined reference to `void printArray<int>(int*, int)'
collect2: ld returned 1 exit status
========= code of case 2 =========
help.h
1 2 3 4 5 6 7 8
|
#ifndef HELP_H_
#define HELP_H_
template<class TYPE>
void
printArray(TYPE *s, int n);
#endif // HELP_H_
|
help.cc
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
template<class TYPE>
void
printArray(TYPE *s, int n)
{
if (n <= 0)
return;
cout << "Array:";
for (int i = 0; i < n; i++) {
cout << " " << s[i];
}
cout << endl;
}
|
sortexp.cc
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include "help.h"
using namespace std;
int main() {
int s[] = {5, 4, 7, 2, 2, 3};
int n = sizeof(s) / sizeof(s[0]);
cout << "size of s is " << n << endl;
printArray(s, n);
return 0;
}
|
============================================
Any comments? Many thanks,