Hi, On Tue, May 31, 2011 at 05:59:40AM +0000, Her, Il wrote: > From: Ian Lance Taylor [mailto:iant@xxxxxxxxxx] >> "Her, Il" <il.her@xxxxxx> writes: >> >>> I experienced "undefined reference to template function ." when I am >>> compiling my program with gcc 4.1.2. >>> >>> Almost everyone says that's because template functions weren't be >>> implemented in the same unit where they are prototyped. (I used .cpp >>> file for implementation and .h file for declaration). >>> >>> But, It works if I use gcc 3.4.6 compiler without any change of >>> options. Why is this happening?... >>> I am working with my customer, I can't make them understand the >>> common rule for using template because it works on gcc 3.4.6. >>> >>> Can you explain this situation to me? >>> (Something like it is changed after 4.0 or you have any options to avoid this.) >> >> It's impossible to give you a precise answer without a small example. >> >> You may find it helpful to read >> http://gcc.gnu.org/onlinedocs/gcc-4.6.0/gcc/Template-Instantiation.html > > [...] > > ** Result of compiling > [test@test-1] $ g++ -c -dynamic sub.cpp > [test@test-1] $ g++ -shared -o libsub.so sub.o > [test@test-1] $ g++ -g -W -o main main.cpp -lsub -L./ > /tmp/ccaUlqlQ.o: In function `main`: > /home/guinsa/main.cpp:10: undefined reference to `Base<TEST>::dump(TEST&)` > /home/guinsa/main.cpp:11: undefined reference to `Base<TEST>::fn(int, int)` > collect2: ld returned 1 exit status To my knowledge it's impossible. You want to compile a library which contains the "template code", and which is fully independent of the type TEST for which you instantiate the template Base<...>. If that would be possible, we could rewrite the complete C++ standard library and compile it into a shared library :-) I think, you have two ways to solve it: 1) really include also the template implementations in "sub.cpp" into main.cpp 2) Instantiate explicitely the necessary templates. In your example, you would need a line template class Base<TEST>; somewhere in a file which includes the implementations. You could e.g. add to sub.cpp the two lines (it's not necessary to include TEST.h) struct TEST; template class Base<TEST>; or generate a special "template instantiation library" (as proposed on http://gcc.gnu.org/onlinedocs/gcc-4.6.0/gcc/Template-Instantiation.html). Axel