-1

Why this code compiles using g++ 5.2.1, but fails with 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 compilation:

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

Compilation successfull.

4.9.3 compilation:

$ 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;
....

Solution is to add #include <stdexcept> to exception.h

Now it works with both versions.

When I remove #include <iostream> from main.cpp, then compilation fails even with 5.2.1 version and #include <stdexcept> is required too.

Why this code works on 5.2.1 version without including stdexcept header?

It's included in iostream on 5.2.1 version but not in 4.9.3 version? Reading GCC changes didn't help.

Enkelli
  • 305
  • 5
  • 18
  • 4
    C++ only specifies what happens when you follow the rules (which say that you must include the correct header). C++ does not specify what happens when you *don't* follow the rules. C++ can therefore not answer your question, nor is the answer terribly enlightening. Just follow the fine rules. – Kerrek SB Apr 07 '16 at 20:18
  • I hoped there is some good reason I couldn't figure out. Thanks for explanation. – Enkelli Apr 07 '16 at 20:27

1 Answers1

2

The standard library headers are allowed to include other headers, but there are no guarantees.

Back in the ancient days of g++ 4.0 and 4.1, you could pull in most of the standard library with just #include <iostream> and #include <deque>. But that stopped working in version 4.3 (or something like that).

In order for your code to be portable it should explicitly include all the required headers.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • 3
    "but there are no guarantees" - with [a few exceptions](http://stackoverflow.com/questions/26614983/which-headers-in-the-c-standard-library-are-guaranteed-to-include-another-head). – T.C. Apr 07 '16 at 20:21