delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/11/30/05:36:39.1

From: Jason Green <news AT jgreen4 DOT fsnet DOT co DOT uk>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: RHIDE C++ project link failure
Date: Thu, 30 Nov 2000 00:33:45 +0000
Organization: Customer of Energis Squared
Lines: 64
Message-ID: <uu5b2to3fatj97uuh3gfqejhuouv9uln7q@4ax.com>
References: <9033kq$4u10 AT NWNEWS DOT PCT DOT EDU>
NNTP-Posting-Host: modem-2.sulfur.dialup.pol.co.uk
Mime-Version: 1.0
X-Trace: newsg4.svr.pol.co.uk 975544421 9476 62.136.15.2 (30 Nov 2000 00:33:41 GMT)
NNTP-Posting-Date: 30 Nov 2000 00:33:41 GMT
X-Complaints-To: abuse AT theplanet DOT net
X-Newsreader: Forte Agent 1.7/32.534
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

"Per Pettersson" <ostybosty AT hotmail DOT com> wrote:

> I am an intermediate programmer, trying to make a general template list
> class in C++. The class itself works fine, but when I try to run a test
> program for it, it compiles but it won't link.
> 
> I have three files: list.h with class declaration, list.cpp with class
> definition and main.cpp with test routines, all in the same project. I
> #include "list.h" in both .cpp sources, but no matter what I do, compilation
> of main.cpp fails, with error messages like I hadn't #included the header at
> all ("undefined reference" to the class and all its methods). I tried
> changing the linking order, but no difference.

This is not a DJGPP problem.  It is in fact a C++ FAQ.

Class templates do not compile as a normal class, due to the infinite
number of possibilities, so you can't link to it either.

Instead, the class implementation must be visible to the compiler when
you use the class.  I.e. put the class definition *and* implementation
in list.h and lose list.cpp.

> The funny thing is that, if I put the main() function in list.cpp (where it
> most definitely doesn't belong!) the program will link just fine. I can't
> seem to figure out why this is?

Yep, that would work.  Can you see why now?

> (list.h)
> ---------
> #ifndef _OYP_LIST_H_
> #define _OYP_LIST_H_
> 
> namespace OYP
> {
>   template <class T>
>   class List
>   {
>     // tons of declarations...
>   };

class implementation goes here.

> }
> 
> #endif
> 

delete list.cpp...

> (list.cpp)
> ----------
> #include "list.h"
> 
> using OYP::List;
> 

and insert this to list.h...

> template <class T>
> List<T>::List()
> {
>   // code
> }

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019