g++ linking problem with using template

P

pembed2003

hi all,
i have a template class that looks like:

******
foo.h:
******

#ifndef _FOO_H_
#define _FOO_H_

template<class T>
class Foo{
public:
...
privdate:
...
};

#endif

*********
foo.cpp:
*********

#include "foo.h"

template<class T>
Foo<T>::Foo(){
...
}

template<class T>
Foo<T>::~Foo(){
...
}

i compiled that into a foo.o with:

g++ -c foo.cpp

and then i have a driver:

#include "foo.h"

int main(int argc,char** argv){
Foo<int> f;
}

and i compile the driver with:

g++ driver.cpp foo.o -o driver

but there is error:

/tmp/c8KKKLKD.o(.text+0x19): In function `main':
:undefined reference to `Foo<int>::Foo[in-charge]()'
.... etc

if i send the same problem to a VC++ compiler, it compiles ok. why is
g++ not able to compile the program? why can't it find the
constructor, i already supply foo.o so it should find the function
there.

any help? thanks!
 
E

E. Robert Tisdale

pembed2003 said:
i have a template class that looks like:

******
foo.h:
******

#ifndef _FOO_H_
#define _FOO_H_

template<class T>
class Foo{
public:
...
privdate:
...
};

#endif

*********
foo.cpp:
*********

#include "foo.h"

template<class T>
Foo<T>::Foo(){
...
}

template<class T>
Foo<T>::~Foo(){
...
}

i compiled that into a foo.o with:

g++ -c foo.cpp

and then i have a driver:

#include "foo.h"

int main(int argc,char** argv){
Foo<int> f;
}

and i compile the driver with:

g++ driver.cpp foo.o -o driver

but there is error:

/tmp/c8KKKLKD.o(.text+0x19): In function `main':
:undefined reference to `Foo<int>::Foo[in-charge]()'
... etc

if i send the same problem to a VC++ compiler, it compiles ok. why is
g++ not able to compile the program? why can't it find the
constructor, i already supply foo.o so it should find the function
there.

Type

info gcc

and search for Template Instantiation.

Post this question to the gnu.g++.help newsgroup.

Explicitly instantiate Foo<int> in your foo.cpp source file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top