Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No compiler error on using garbage characters in #include statement

#include <iostream> gfhgfhgf
using namespace std;

int main() {
    return 0;
}

Why does this code snippet compile? As per The gcc reference on Include Syntax:

It is an error if there is anything (other than comments) on the line after the file name.

and that's exactly what's being done in the code.

like image 783
Zoso Avatar asked Jan 07 '15 10:01

Zoso


1 Answers

Using the -pedantic-errors flags in gcc and clang turns this into an error see it live:

error: extra tokens at end of #include directive
#include <iostream> gfhgfhgf
                    ^

which indicates it is an extension.

If we look at the Interfacing C and TAL In The Tandem Environment they have some code like this:

#include <stdlibh> nolist
                   ^^^^^^

So both gcc and clang support extra characters after the include directive to support an extension needed on some platforms. Using the -pedantic flags makes gcc and clang produce a warning for extensions that violate the standard and as noted above you can use -pendatic-errors to turn this into an error (emphasis mine):

to obtain all the diagnostics required by the standard, you should also specify -pedantic (or -pedantic-errors if you want them to be errors rather than warnings).

We can find a reference for the nolist extension in the HP'sC/C++ Programmers guide for NonStop Systrms which says:

nolist
  directs the compiler not to list the contents of the file or sections
  being included.
This is an HP NonStop  extension to the standard.

Note, the draft C++ standard defines the grammar for this form of include in section 16.2 [cpp.include] as follows:

# include < h-char-sequence> new-line
like image 140
Shafik Yaghmour Avatar answered Sep 29 '22 06:09

Shafik Yaghmour