程序以g ++编译,但在gcc中以链接器错误退出

nag*_*gul 3 c++ gcc templates g++

我正在尝试解决有关专门模板类问题.

这个代码用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
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

小智 15

使用gcc编译时,默认情况下不会链接C++库.始终使用g ++构建C++代码.

  • 是的确如此,但它没有链接C++库.你的问题是链接,而不是编译. (6认同)
  • 您可以将-lstdc ++与gcc一起使用来获取(gcc -lstdc ++ my.cpp)中链接的标准库和运行时. (4认同)

Kei*_*thB 6

如果您想亲眼看到差异,请尝试使用-v标志的两个版本

$ g++ -v traits2.cpp
$ gcc -v traits2.cpp
Run Code Online (Sandbox Code Playgroud)

这将显示代码顶部可执行文件中的每个步骤,包括添加的库.