template programming problem

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,
Last edited on
Back in 98, there used to be a keyword in the standard that let you define and declare a template function in different translation units. It was taken out because implementing it was so complex that only one compiler ever supported it.

Templates work a bit like macros. The compiler needs to see the template definition in order to figure out how to instantiate the function for each specific call, and whether the call is legal given the definition of the template. Since compilation of C++ code is done in independent translation units that don't affect each other until link time, you have to declare and define template functions in the same file.
Topic archived. No new replies allowed.