Программы компилируются в g ++, но завершаются с ошибками компоновщика в gcc - PullRequest
3 голосов
/ 03 августа 2009

Я пробую решение на вопросе о специализированных шаблонных классах .

Этот код прекрасно компилируется в g ++, но выдает ошибки компоновщика при компиляции с gcc. В чем причина этих ошибок?

$ 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

Файл traits2.ccp содержит вышеупомянутое решение с функцией emtpy main ():

#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;
}

Ответы [ 3 ]

15 голосов
/ 03 августа 2009

Когда вы компилируете с помощью gcc, библиотеки C ++ по умолчанию не связаны. Всегда создавайте код C ++ с помощью g ++.

6 голосов
/ 03 августа 2009

Если вы хотите увидеть разницу сами, попробуйте обе версии с флагом -v

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

Это покажет вам каждый из шагов из исполняемого кода, включая добавленные библиотеки.

0 голосов
/ 03 августа 2009

Ваш код на C ++, поэтому он должен быть скомпилирован с g ++, компилятором C ++, а не gcc, компилятором C.

...