How to make template classes in .o files work?

B

Boltar

Hi

I have a template class thats defined in a header file and implemented
in a .cpp module that is compiled to a .o file. No problems there. But
when I try to use this class from another .o file I get undefined
error messages from the linux linker, eg: cl_foo<int>(...) not
defined.

Presumbly this is because theres no actual instance of cl_foo<int>
created in the .o file that contains the template class. Is there a
way of getting the linker to use a bit of brains and create it on the
fly or do I have to just put the entire template class implementation
in a header file and #include it everywhere I need it (which seems a
bit archaic)?

Thanks for any help

B2003
 
R

Rolf Magnus

Boltar said:
Hi

I have a template class thats defined in a header file and implemented
in a .cpp module that is compiled to a .o file. No problems there. But
when I try to use this class from another .o file I get undefined
error messages from the linux linker, eg: cl_foo<int>(...) not
defined.

Presumbly this is because theres no actual instance of cl_foo<int>
created in the .o file that contains the template class.

That's the reason.
Is there a way of getting the linker to use a bit of brains and create it
on the fly

No. The linker would have to see the source code and provide it to the
compiler somehow to let it generate the code. I don't know if any toolchain
does that. If by "the linux linker", you mean the GNU linker, then no, it
can't do that.
or do I have to just put the entire template class implementation
in a header file and #include it everywhere I need it (which seems a
bit archaic)?

Well, you can still put the implementation in a .cpp file and then #include
that at the end of your header. Another alternative, if the set of template
instances is known in the place where the template is defined, you can use
explicit template instantiation to make the compiler generate those
template instances that you need.
 
B

Boltar

Well, you can still put the implementation in a .cpp file and then #include
that at the end of your header. Another alternative, if the set of template
instances is known in the place where the template is defined, you can use
explicit template instantiation to make the compiler generate those
template instances that you need.

Good idea, I'll try that. Thanks.

B2003
 
D

Dave Rahardja

Good idea, I'll try that. Thanks.

Note that explicitly instantiating those templates mean that your
library user's code can't instantiate other instances for themselves.
This may or may not be what you want.

-dr
 

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

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top