Re: ld returned 1 exit status Error
"pai" <grpai1@yahoo.com> wrote in message
news:b68ddf08-0243-4a51-8280-bd59295101cc@2g2000hsn.googlegroups.com...
Hi All,
I am getting this error when I compile. Can any one tell wht
mistake i have done.
I am using 4 files
[SNIP]
---------------
vector.cpp
--------------
#include "vector.h"
template <class T>
T* ptl::vec<T>::allocate(int size)
{
T *tmp = (T*)malloc(size);
cout << "allocate fn" << endl;
return tmp;
}
[SNIP]
undefined reference to `ptl::vec<int>::allocate(int)'
[SNIP]
Your problem is vector.cpp. You have "hidden" the template to create
vec::allocate from the compiler, when it is compiling the main.cpp. You
have two choices. Either move the content of vector.cpp (the allocate
function) into the vector.,h file, OR instantiate explicitly
vector<int>::alocate into the vector.cpp file. The latter "solution" is
rather an ugly hack, so my suggestion is to simply put the template into the
header.
Why is this happening? A template is just a ... template. A class template
is not a class, it's member functions, such as allocate here, and not
functions. They are template that can be used to create the class/member
functions. That creation is called instantiation. The complier needs to
see the template in order to automagically instantiate it for you. However,
when your compiler compiles main.cpp it can only see what is in vector.h;
and the template to create the allocate member function is not there! So it
cannot instantiate that member function for the vector of ints. When it
complies vector.cpp it can see the template, but the compiler has no clue
(at that time) that you need an int vector: so it does nothing. Your
vector.o is "empty". By putting the implementation (function body) of
allocate into the header you give the compiler the cookie-cutter that it can
use to make the allocate function for you int vector. It will magically be
included into main.cpp, but that won't be a problem. Template
instantiations are weak symbols, so even if there will be (in a larger
program) a vector<int>::allocate inside many object files (you will only
have it now in main.o) the linker will just pick the first one it can see
and disregard the rest.
I hope this helps.
ww (Attila)
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]