1

class.h

#include <iostream>
#include <stdint.h>

using namespace std;

template <typename T>
class CIntegerType {
 public:
    void Show ( void );

 private:
    T m_Data;
};

class.cpp

#include "class.h"

template <typename T>
void CIntegerType<T> :: Show ( void ) {
    cout << m_Data << endl;
}

main.cpp

#include "class.h"

int main ( void ) {
    CIntegerType<uint32_t> UINT32;

    UINT32 . Show ();

    return 0;
}

This commands return:

g++ -Wall -pedantic -c main.cpp

g++ -Wall -pedantic -c class.cpp

g++ -Wall -pedantic -o class.o main.o

main.o: In function `main': main.cpp:(.text+0x11): undefined reference to 'CIntegerType< unsigned int>::Show()' collect2: ld returned 1 exit status

Peter K.
  • 151
  • 2
  • 13
  • 1
    g++ -Wall -pedantic **-o class.o** main.o -- Looks like you're missing an argument – Steven Maitlall May 28 '13 at 20:37
  • You might need to switch the objects around, My memory fails me but I think you must always specify your main loop object first when compiling. – Syntactic Fructose May 28 '13 at 20:42
  • Try putting the template function in the header. See: http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – shawn May 28 '13 at 21:37

2 Answers2

1

Try g++ -Wall -pedantic -o main.o class.o instead. You are facing the same problem as in this question: g++ linking order dependency when linking c code to c++ code

The linker searches for functions in the order they appear. Since you have a template function, its use in main must be fed to the linker prior to the actual code to instantiate it in class.

Community
  • 1
  • 1
Marc Claesen
  • 16,778
  • 6
  • 27
  • 62
  • Thanks. I tried it. Output: /usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 12 ... : In function `_start': (.text+0x18): undefined reference to `main' collect2: ld returned 1 exit status – Peter K. May 28 '13 at 20:45
  • I tried both variant "g++ -Wall -pedantic -o main.o class.o" and "g++ -Wall -pedantic -o class.o main.o", but no result. – Peter K. May 28 '13 at 20:50
1

Try putting your template implementation in the header file.

See: Why can templates only be implemented in the header file?

Community
  • 1
  • 1
shawn
  • 336
  • 1
  • 3