Linking code with templates and template libraries

B

bav.272304

I have a code which uses external library with templates. The separate
compiling of project files gets definition of the same symbols in
different object files, so linking fails.

Actually, library uses templates only internally, and each
recompilation does not add anything new.

How should I fix it? Should I drop the templates from library?
 
J

John Harrison

I have a code which uses external library with templates. The separate
compiling of project files gets definition of the same symbols in
different object files, so linking fails.

Actually, library uses templates only internally, and each
recompilation does not add anything new.

How should I fix it? Should I drop the templates from library?

Either

1) Drop templates.

2) Put template code in header files.

If you want a library of templates, 2 is the ONLY option. It's how the
STL works.

john
 
S

siddhu

probably you can use explicit intantiation technique.

e.g.

If you have a template function declared in a.h as

template<typename T>
void print(const T&);

and defined in a.c as

template<typename T>
void print(const T&)
{
......
}

Keep prepocessor guards in all the file which have to be #included
(a.h,a.c in this case).

Then you can have separate .h file say b.h in which you can explicitly
instantiate it as

//b.h
#include "a.c"

template void print<double/*Or whatever as per your implementation*/
(const double&);

Link it with your test file.


//test.cpp

#include "a.h"

int main()
{
double d = 0.0;
print(d);
}

This method can also be used for class templates,member
functions,Template member functions.

Regards,
Siddhu
 

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
473,969
Messages
2,570,161
Members
46,709
Latest member
AustinMudi

Latest Threads

Top