views:

528

answers:

3

I'm trying out the solution to a question about specialized template classes.

This code with a compiles fine in g++, but throws up linker errors when compiled with gcc. What's the cause of these errors ?

$ g++ traits2.cpp
$ gcc traits2.cpp
/tmp/ccI7CNCY.o: In function `__static_initialization_and_destruction_0(int, int)':
traits2.cpp:(.text+0x36): undefined reference to `std::ios_base::Init::Init()'
traits2.cpp:(.text+0x3b): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccI7CNCY.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status

The traits2.ccp file contains the aforementioned solution with an emtpy main() function:

#include <iostream>

using namespace std;

// A default Traits class has no information
template<class T> struct Traits
{
};

// A convenient way to get the Traits of the type of a given value without
// having to explicitly write out the type
template<typename T> Traits<T> GetTraits(const T&)
{
    return Traits<T>();
}

template <int major, int minor> struct A 
{ 
    void f() 
    { 
        cout << major << endl; 
    }   
};

// Specialisation of the traits for any A<int, int>
template<int N1, int N2> struct Traits<A<N1, N2> >
{
    enum { major = N1, minor = N2 };
};

template <> struct A<4,0> 
{       
    void f() 
    { 
        cout << "Specialized:" << GetTraits(*this).major << endl; 
    }   
};

int main(int argc, char * argv[] )
{
    /*
    A<4,0> p;
    A<1,2> p2;
    p.f();
    p2.f();
    */
    return 1;
}
+2  A: 

Your code is C++, so it must be compiled with g++, the C++ compiler, not gcc, the C compiler.

Nick Meyer
You can compile C++ code with gcc, but it won't link for you automatically.
anon
You can use -lstdc++ with gcc to get the standard libraries and runtime linked in (gcc -lstdc++ my.cpp).
Max Lybbert
+10  A: 

When you compile with gcc, the C++ libraries are not linked in by default. Always build C++ code with g++.

anon
Isn't gcc supposed to automatically invoke the C++ compiler for .cpp files: http://stackoverflow.com/questions/172587/what-is-the-difference-between-g-and-gcc ?
nagul
Yes it does, but it doesn't link the C++ libraries. Your problem is with linking, not compiling.
anon
You can use -lstdc++ with gcc to get the standard libraries and runtime linked in (gcc -lstdc++ my.cpp).
Max Lybbert
+3  A: 

If you want to see the difference for yourself, try both versions with the -v flag

$ g++ -v traits2.cpp
$ gcc -v traits2.cpp

This will show you each of the steps from code top executable, including the libraries that are added.

KeithB