簡體   English   中英

程序以g ++編譯,但在gcc中以鏈接器錯誤退出

[英]Programs compiles in g++ but exits with linker errors in gcc

我正在嘗試解決 有關專門模板類問題

這個代碼用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;
}

使用gcc編譯時,默認情況下不會鏈接C ++庫。 始終使用g ++構建C ++代碼。

如果您想親眼看到差異,請嘗試使用-v標志的兩個版本

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

這將顯示代碼頂部可執行文件中的每個步驟,包括添加的庫。

您的代碼是C ++,因此必須使用g ++,C ++編譯器,而不是gcc,C編譯器進行編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM