473,654 Members | 3,043 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

template compile errors

Hi,
I'm trying to create a simple stack class using C++ and templates.
Everything works well and good if I amke the class totally inline.
However, as soon as I try to seperate the class into a .h and a .cpp
file, gcc throws some strange linking errors.

Compiling like this:

gcc test.cpp stackList.cpp -lstdc++ -o test

produces these errors:

/tmp/ccCJLrbl.o(.tex t+0x84): In function `main':
: undefined reference to `Stack<int>::St ack[in-charge]()'
/tmp/ccCJLrbl.o(.tex t+0x101): In function `main':
: undefined reference to `Stack<int>::pu sh(int)'
/tmp/ccCJLrbl.o(.tex t+0x10c): In function `main':
: undefined reference to `Stack<int>::si ze() const'
/tmp/ccCJLrbl.o(.tex t+0x18b): In function `main':
: undefined reference to `Stack<int>::em pty() const'
/tmp/ccCJLrbl.o(.tex t+0x19c): In function `main':
: undefined reference to `Stack<int>::si ze() const'
/tmp/ccCJLrbl.o(.tex t+0x1aa): In function `main':
: undefined reference to `Stack<int>::po p()'
/tmp/ccCJLrbl.o(.tex t+0x20f): In function `main':
: undefined reference to `Stack<int>::~S tack [in-charge]()'
/tmp/ccCJLrbl.o(.tex t+0x229): In function `main':
: undefined reference to `Stack<int>::~S tack [in-charge]()'
collect2: ld returned 1 exit status
I'm tearing my hair out... why would it not work in seperate files? My
class definition is something like this:

template <class T>
class Stack
{
private:
StackNode<T> *stackHead;
/// The number of elements on the stack. It's easier to keep count
/// of them here than to count them every time we need them.
unsigned int stackSize;
protected:
public:
/// Default constructor: set the stackSize to be 0.
Stack(void);

/// Default destructor: clean up any memory allocated.
~Stack(void);
/// push: push an item onto the stack, and incrememt the size.
bool push(T item);

/// pop: return the topmost element from the stack, removing it
from the stack at the same time:
T pop(void);

/// size: returns how many items are on the stack:
unsigned int size(void) const;
/// empty: return true if the stack is empty:
bool empty(void) const;
/// full: return true if the stack is full: - for a linked list
implementation, this can be safely ignored:
bool full(void) const;

};
and the code for a single method for the above class looks like this:

template <class T> bool Stack<T>::push( T item)
{
if (full())
return false;

StackNode<T> *node = new StackNode<T> (item);
node->Head = stackHead;
stackHead = node;
stackSize++;

return true;
}

I've been following the C++ language tutorial, and a few books I own
at home. It looks like I'm doing everything properly... Can anyone
shed some light on this?
Thanks,
Jul 22 '05 #1
4 2337


Thomi Richards wrote:
Hi,

I'm trying to create a simple stack class using C++ and templates.
Everything works well and good if I amke the class totally inline.
However, as soon as I try to seperate the class into a .h and a .cpp
file, gcc throws some strange linking errors.

Compiling like this:

gcc test.cpp stackList.cpp -lstdc++ -o test

produces these errors:

/tmp/ccCJLrbl.o(.tex t+0x84): In function `main':
: undefined reference to `Stack<int>::St ack[in-charge]()'
/tmp/ccCJLrbl.o(.tex t+0x101): In function `main':
: undefined reference to `Stack<int>::pu sh(int)'
/tmp/ccCJLrbl.o(.tex t+0x10c): In function `main':
: undefined reference to `Stack<int>::si ze() const'
/tmp/ccCJLrbl.o(.tex t+0x18b): In function `main':
: undefined reference to `Stack<int>::em pty() const'
/tmp/ccCJLrbl.o(.tex t+0x19c): In function `main':
: undefined reference to `Stack<int>::si ze() const'
/tmp/ccCJLrbl.o(.tex t+0x1aa): In function `main':
: undefined reference to `Stack<int>::po p()'
/tmp/ccCJLrbl.o(.tex t+0x20f): In function `main':
: undefined reference to `Stack<int>::~S tack [in-charge]()'
/tmp/ccCJLrbl.o(.tex t+0x229): In function `main':
: undefined reference to `Stack<int>::~S tack [in-charge]()'
collect2: ld returned 1 exit status

I'm tearing my hair out... why would it not work in seperate files? My
class definition is something like this:

template <class T>
class Stack
{
private:
StackNode<T> *stackHead;
/// The number of elements on the stack. It's easier to keep count
/// of them here than to count them every time we need them.
unsigned int stackSize;
protected:
public:
/// Default constructor: set the stackSize to be 0.
Stack(void);

/// Default destructor: clean up any memory allocated.
~Stack(void);
/// push: push an item onto the stack, and incrememt the size.
bool push(T item);

/// pop: return the topmost element from the stack, removing it
from the stack at the same time:
T pop(void);

/// size: returns how many items are on the stack:
unsigned int size(void) const;
/// empty: return true if the stack is empty:
bool empty(void) const;
/// full: return true if the stack is full: - for a linked list
implementation, this can be safely ignored:
bool full(void) const;

};

and the code for a single method for the above class looks like this:

template <class T> bool Stack<T>::push( T item)
{
if (full())
return false;

StackNode<T> *node = new StackNode<T> (item);
node->Head = stackHead;
stackHead = node;
stackSize++;

return true;
}

I've been following the C++ language tutorial, and a few books I own
at home. It looks like I'm doing everything properly... Can anyone
shed some light on this?

Thanks,


code for a template doesn't really exist until you instantiate it... in
a very raw sense they are kind of like
macros in that regard. Until you use them, no code or data gets
generated. If you just take part of a group of template definitions and
stick them in a C++ file, no code will be generated in the file, and you
end up with essentially the same problem as if you are working in C and
move all the global #defines into a C language source file, they just
wouldn't be accessible. What happens when you instantiate a template is,
the compiler takes all the structures and functions you have declared
related to the template and tries to make functions out of them, using the
instantiated types instead of the placeholder types you used when you
declared the template. So you can instantiate one template using many
many different types in the course of a single program, but the cost is
that each time you change the types given in the instantiation, the
compiler generates another set of code and data specific to those types.

You might be able to fix this particular problem by instantiating a
template using the <int> type in your source file that you put the
templates in, that may at least cause the functions to get declared so
they will appear at link time. However, that means that for every time
you want to use that template with a different type, you've got to go into
your source file and instantiate it deliberately. Since that really cuts
down on the power of templates dramatically, it is usually recommended you
just group all the template functions and so forth in header files, but of
course that is its own problem since if you are modifying global headers
very often it can force you to recompile large parts of your project on a
regular basis.

David
Jul 22 '05 #2
Thomi Richards wrote:
I'm trying to create a simple stack class using C++ and templates.
Everything works well and good if I amke the class totally inline.
However, as soon as I try to seperate the class into a .h and a .cpp
file, gcc throws some strange linking errors.

Compiling like this:

gcc test.cpp stackList.cpp -lstdc++ -o test

produces these errors:

/tmp/ccCJLrbl.o(.tex t+0x84): In function `main':
: undefined reference to `Stack<int>::St ack[in-charge]()'
/tmp/ccCJLrbl.o(.tex t+0x101): In function `main':
: undefined reference to `Stack<int>::pu sh(int)'
/tmp/ccCJLrbl.o(.tex t+0x10c): In function `main':
: undefined reference to `Stack<int>::si ze() const'
/tmp/ccCJLrbl.o(.tex t+0x18b): In function `main':
: undefined reference to `Stack<int>::em pty() const'
/tmp/ccCJLrbl.o(.tex t+0x19c): In function `main':
: undefined reference to `Stack<int>::si ze() const'
/tmp/ccCJLrbl.o(.tex t+0x1aa): In function `main':
: undefined reference to `Stack<int>::po p()'
/tmp/ccCJLrbl.o(.tex t+0x20f): In function `main':
: undefined reference to `Stack<int>::~S tack [in-charge]()'
/tmp/ccCJLrbl.o(.tex t+0x229): In function `main':
: undefined reference to `Stack<int>::~S tack [in-charge]()'
collect2: ld returned 1 exit status
I'm tearing my hair out... why would it not work in seperate files?
My class definition is something like this:

template <class T>
class Stack
{
private:
StackNode<T> *stackHead;
/// The number of elements on the stack. It's easier to keep count
/// of them here than to count them every time we need them.
unsigned int stackSize;
protected:
public:
/// Default constructor: set the stackSize to be 0.
Stack(void);

/// Default destructor: clean up any memory allocated.
~Stack(void);
/// push: push an item onto the stack, and incrememt the size.
bool push(T item);

/// pop: return the topmost element from the stack, removing it
from the stack at the same time:
T pop(void);

/// size: returns how many items are on the stack:
unsigned int size(void) const;
/// empty: return true if the stack is empty:
bool empty(void) const;
/// full: return true if the stack is full: - for a linked list
implementation, this can be safely ignored:
bool full(void) const;

};
and the code for a single method for the above class looks like this:

template <class T> bool Stack<T>::push( T item)
{
if (full())
return false;

StackNode<T> *node = new StackNode<T> (item);
node->Head = stackHead;
stackHead = node;
stackSize++;

return true;
}
Since you didn't tell us, I'll suppose that
you moved the function template definitions
from your stackList.h header file
to your stackList.cpp source file and that
you include'd the stackList.h header file
but *not* the stackList.cpp source file
in your test.cpp source file.

Please allow me to ask a simple question,

"How does the C++ compiler know
where to find the function template definitions
so that it can instantiate them
when it is compiling test.cpp?"
I've been following the C++ language tutorial,
and a few books I own at home. info gcc 'C++ extensions' 'Template Instantiation' It looks like I'm doing everything properly...
Can anyone shed some light on this?


If you know all of the template functions that you need.
you can instantiate the template functions *explicitly*:

template Stack<int>::Sta ck(void);
template std::bool Stack<int>::pus h(int);
template size_t Stack<int>::siz e(void) const;
template std::bool Stack<int>::emp ty(void) const;
template int Stack<int>::pop (void);
template void Stack<int>::~St ack(void);

right after the function template definitions
in your stackList.cpp source file.
Jul 22 '05 #3
"Thomi Richards" <th***@thomi.im ail.net.nz> wrote in message
news:dc******** *************** ***@posting.goo gle.com...
Hi,
I'm trying to create a simple stack class using C++ and templates.
Everything works well and good if I amke the class totally inline.
However, as soon as I try to seperate the class into a .h and a .cpp
file, gcc throws some strange linking errors.
[...]
I'm tearing my hair out... why would it not work in seperate files? My
class definition is something like this:
[...]


See the FAQ (http://www.parashift.com/c++-faq-lite/), section 34 ("Container
classes and templates"), question 12 ("Why can't I separate the definition
of my templates class from it's declaration and put it inside a .cpp file?")
and the related questions that follow.

--
David Hilsee
Jul 22 '05 #4
Ahh,

Thanks for that.
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4812
by: Ben | last post by:
Hi all. I'm trying to make a third party lib (Rogue Wave's math.h++) compile (under VC7) and I'm having some problems with what I think is code that was written specifically to work with the older (less standard) versions of the VC compiler. There's a class like this (the comments are mine): class RWMathVec
1
3334
by: Oplec | last post by:
Hi, I'm learning C++ as a hobby using The C++ Programming Language : Special Edition by Bjarne Stroustrup. I'm working on chpater 13 exercises that deal with templates. Exercise 13.9 asks for me to turn a previously made String class that deals with char's into a templated String class that uses the template parameter C instead of char. I thought it would be fairly simple to do this exercise, but I encoutered many errors for my...
1
1389
by: terry.jeske | last post by:
Hello, In xalan 2.41 we were able to conditionally call a template. This appears broken in 2.6. I did glance at the call-template specfications but did not see anything that would point to this being a feature or a change to follow a standard. The problem is that if the called template is not included in xslt pass, I get: javax.xml.transform.TransformerException: ElemTemplateElement error: "your missing template name here".
6
3325
by: Ben Ingram | last post by:
Hi all, I am writing a template matrix class in which the template parameters are the number of rows and number of columns. There are a number of reasons why this is an appropriate tradeoff for my particular application. One of the advantages is that the _compiler_ can force inner matrix dimensions used in multiplication to agree. A _complie-time_ error will be triggered if you write A * B and the number of coluns in A does not equal the...
5
2627
by: Ruben Campos | last post by:
Some questions about this code: template <typename T> class MyTemplate; template <typename T> MyTemplate <T> operator- (const MyTemplate <T> & object); template <typename T> MyTemplate <T> operator- (const MyTemplate <T> & object1, const MyTemplate <T> & object2); template <typename T> class MyTemplate
3
3933
by: Chris | last post by:
I am having a very strange problem involving virtual functions in template classes. First of all, here is an extremely simplified structure of the two classes I am having problems with. template<class Type> class base { public: base& operator/=(const base&); Type *image;
2
2193
by: Patrick Kowalzick | last post by:
Hello NG, sorry to bother again, but I am a lit surprised that I got no answer on my post (attached below). So I refined the code a little bit :-). If there is a typedefed class X inside a class Y which has the same typedef name and used in the form "Instance_Y::type::type" MSVC7.1 fails to compile. See example below.
2
2434
by: steve | last post by:
Hi, I'm trying to use a protocol class as a template parameter. The protocol class defines its own types and methods for working with them. The template class uses the types defined by the protocol and various methods, however I get errors when trying to compile this in Xcode while in Codewarrior it works fine. I'm looking for a way to either fix this in Xcode, or find another design solution that meets the needs of the problem.
12
3334
by: nooneinparticular314159 | last post by:
Hello. If I declare the following: template<int a, int b, int SomeArray> class DoSomething{ public: .. .. ..
0
8372
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8285
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8706
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8591
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7304
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6160
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5621
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4293
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1592
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.