代码用g ++ 5.2.1编译,但不用g ++ 4.9.3编译

时间:2016-04-07 20:15:35

标签: c++ gcc g++

为什么此代码使用g++ 5.2.1进行编译,但失败并使用g++ 4.9.3

//exception.h
class MyError: public std::runtime_error
{
    public:
        using std::runtime_error::runtime_error;
};
// nothing else here
//main.cpp
#include <iostream>
#include "exception.h"

int main() {}

5.2.1汇编:

$ g++ --version
g++ 5.2.1
$ g++ -std=c++11 -c main.cpp -o main.o
$ g++ main.o -o a.out

编译成功。

4.9.3汇编:

$ g++ --version
g++ 4.9.3
$ g++ -std=c++11 -c main.cpp -o main.o
$ g++ main.o -o a.out
In file included from main.cpp:2:0:
exception.h:3:1: error: expected class-name before ‘{’ token
 {
 ^
exception.h:5:14: error: ‘std::runtime_error’ has not been declared
using std::runtime_error::runtime_error;
....

解决方案是将#include <stdexcept>添加到exception.h

现在它适用于两个版本。

当我从main.cpp中删除#include <iostream>时,即使使用5.2.1版本,编译也会失败,并且也需要#include <stdexcept>

为什么此代码适用于5.2.1版本而不包含stdexcept标头?

它包含在iostream 5.2.1版本上但不包含在4.9.3版本中?阅读GCC changes并没有帮助。

1 个答案:

答案 0 :(得分:2)

标准库标题允许包含其他标题,但不保证。

回到g ++ 4.0和4.1的古代,你可以只用#include <iostream>#include <deque>拉入大部分标准库。但是那停止了4.3版本(或类似的东西)。

为了使您的代码可移植,它应明确包含所有必需的标头。

相关问题