RE: Undefined reference to template function ...

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Thank you for answering my question.
Here is my sample.

[Test.h]
#ifndef __TEST_hh
#define __TEST_hh
struct TEST
{
	int a, b;
};
#endif

[sub.h]
#include <stdio.h>
template <typename T> struct Base
{
	void dump(T &r);
	int fn(int a, int b);
};

[sub.cpp]
#include "sub.h"

template<typename T> void Base<T>::dump(T &r)
{
}

template<typename T> int Base<T>::fn(int a, int b);
{
	return 0;
}

[main.cpp]
#include <stdio.h>
#include "sub.h"
#include "TEST.h"

int main()
{
	Base<TEST> t;
	TEST x;

	t.dump(x);
	t.fn(1, 2);
}

** 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


Please, help me to solve this.
Thank you.


Her, Il
Technology Consulting
Technology Service Korea

TEL  : +82-2-2199-4475
Mobile : +82-10-4765-5597
il.her@xxxxxx

-----Original Message-----
From: Ian Lance Taylor [mailto:iant@xxxxxxxxxx] 
Sent: Tuesday, May 31, 2011 2:49 PM
To: Her, Il
Cc: gcc-help@xxxxxxxxxxx
Subject: Re: Undefined reference to template function ...

"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

Ian



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux