Find the answer to your Linux question:
Results 1 to 2 of 2
Hello, I'm having a similar problem. I am trying to write some complex code, but was able to reproduce my compiler error in a simplified version of the program. The ...
  1. #1
    Just Joined!
    Join Date
    Feb 2009
    Posts
    1

    undefined reference

    Hello,
    I'm having a similar problem. I am trying to write some complex code, but was able to reproduce my compiler error in a simplified version of the program.
    The issue here is that I am using templates... is there something obvious I am missing here? I've posted my code and compile message below.
    Thanks!

    test.h:
    1 #ifndef TEST_H
    2 #define TEST_H
    3
    4 template <class T>
    5 class test
    6 {
    7 public:
    8 test();
    9 test( T val );
    10 T get_thing();
    11
    12 private:
    13 T thing;
    14 };
    15
    16 #endif


    test.cc:
    1 #include "test.h"
    2
    3 template <class T>
    4 test<T>::test()
    5 {
    6 }
    7
    8 template <class T>
    9 test<T>::test( T val )
    10 {
    11 thing = val;
    12 }
    13
    14 template <class T>
    15 T test<T>::get_thing()
    16 {
    17 return thing;
    18 }
    19


    main.cc:
    1 #include <iostream>
    2 #include "test.h"
    3
    4 using namespace std;
    5
    6 int main()
    7 {
    8 test<int> t = test<int>( 5 );
    9 cout << t.get_thing() << endl;
    10 return 0;
    11 }


    g++ test.cc main.cc -o test
    /tmp/cczsY5Ba.o: In function `main':
    main.cc.text+0x92): undefined reference to `test<int>::test(int)'
    main.cc.text+0x9d): undefined reference to `test<int>::get_thing()'
    collect2: ld returned 1 exit status
    make: *** [all] Error 1

  2. #2
    Just Joined!
    Join Date
    Feb 2009
    Posts
    45
    Quote Originally Posted by mr_snurf
    The issue here is that I am using templates... is there something obvious I am missing here? I've posted my code and compile message below. […]
    test.h: […]
    test.cc: […]
    main.cc: […]
    Code:
    g++ test.cc main.cc -o test
    /tmp/cczsY5Ba.o: In function `main':
    main.cc:(.text+0x92): undefined reference to `test<int>::test(int)'
    main.cc:(.text+0x9d): undefined reference to `test<int>::get_thing()'
    collect2: ld returned 1 exit status
    make: *** [all] Error 1
    GCC is known to have problems when it comes to compiling classes with separated declaration and instantiation. A good description of the problem and possible solutions can be found at:


    Good keywords for searching for further explanations are:
    GCC, template, class, instantiation

    P.S.:
    Please use CODE-tags. Enhances readability tenfold.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...