Find the answer to your Linux question:
Results 1 to 3 of 3
but if I remove all the template stuff, it works. whats going on here? list.cpp Code: #include "list.hh" template <class type> char List<type>::Get( void ) const { return 'a'; } ...
  1. #1
    Linux Newbie
    Join Date
    Mar 2005
    Location
    de_dust
    Posts
    115

    g++ fails on multiple files if there's a template involved...

    but if I remove all the template stuff, it works. whats going on here?

    list.cpp
    Code:
    #include "list.hh"
    
    template <class type>
    char List<type>::Get( void ) const {
      return 'a';
    }
    list.hh
    Code:
    template <class type>
    class List {
    
    public:
      char Get( void ) const;
    };
    try.cpp
    Code:
    #include <stdio.h>
    #include "list.hh"
    
    int main ( void ) {
      List<int> list;
    
      printf("%c\n", list.Get());
      
      return 0;
    }
    g++ list.cpp try.cpp
    Code:
    /tmp/cclUhOCm.o: In function `main':
    try.cpp:(.text+0x11): undefined reference to `List<int>::Get() const'
    collect2: ld returned 1 exit status

  2. #2
    Just Joined!
    Join Date
    Feb 2006
    Posts
    13
    For templates don't have a separe .cpp file.

    Put your implementations inside the .h file itself, it will work.

    Hope this helps.

  3. #3
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    Actually, you can implement a template instance as you did in list.cpp for List<int>::Get(void). However, you need to link it (list.o) specifically to make the executable since the List<int>::Get(void) method will not be automatically instantiated. In fact, every instantiated type of List will have to have its Get() method explicitly instantiated. Not a generally good use of templates, though legal.
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

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