[prog] C++ strange linking behaviour

Kathryn Hogg kjh at flyballdogs.com
Tue Nov 9 01:23:44 EST 2004


Wolfgang Petzold said:
> 	g++ -Wall -g -c -o main.o main.cxx

This is fine.

> 	g++ -Wall -g -c -o someclass.o someclass.cxx

This is the crux of the problems.  someclass.cxx only contains template
definitions.  As such, compiling this file doesn't really do anything.

Furthermore, the way that template instantiation works on most platforms
requires that you see all the template definitions at compile times.  So
all the code in someclass.cxx should be in the header file.

You can either move it into someclass.h or just add
#include "someclass.cxx" to the bottom of the .h.  That way, if you end up
working with a compiler that uses the cfront method of instantiation, it
will be easier to port.

> The really strange thing about it is, if I copy the main() function
> into the someclass.cxx file, compilation and linking work silently
> and the resulting program prints "is: some string representation"
> as expected.

This works because you've introduced some non-template code that happens
to instantiate PrintableSet<int>  into someclass.cxx.


BTW, for printing containers try the following

std::set<int> s;

std::copy(s.begin(), s.end(), std::ostream_iterator<int>(cout, " "));


or if you just want to do

std::cout << s << std::endl;

try

template <class T>
struct printer
{
    const T &t;
    char char *sep;
    printer(const T &_t, const char *s = " "): t(_t), sep(s)
    {}
}

template <class T>
ostream &operator << (ostream &os, const printer<T> &p>
{
     std::copy(p.t.begin(); p.t.end(),
               std::ostream_iterator<T>(os, p.t.sep);
     return os;
}


and then call

std::cout << printer<int>(s) << std::endl;



-- 
Kathryn
http://womensfooty.com



More information about the Programming mailing list