程序在 g++ 中编译,但在 gcc 中因链接器错误而退出 [英] Programs compiles in g++ but exits with linker errors in gcc

查看:20
本文介绍了程序在 g++ 中编译,但在 gcc 中因链接器错误而退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 解决方案-template-parameters-in-specialized-te">关于专门模板类的问题.

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

此代码在 g++ 中编译良好,但在使用 gcc 编译时会引发链接器错误.这些错误的原因是什么?

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

traits2.ccp 文件包含上述 解决方案 使用 emtpy main() 函数:

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

推荐答案

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

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

这篇关于程序在 g++ 中编译,但在 gcc 中因链接器错误而退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆