Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#include headers in C/C++

After reading several questions regarding problems with compilation (particularly C++) and noticing that in many cases the problem is a missing header #include. I couldn't help to wonder in my ignorance and ask myself (and now to you):

Why are missing headers not automatically checked and added or requested to the programmer?

Such feature is available for Java import statements in Netbeans for example.

like image 626
Carlos Avatar asked Mar 22 '10 14:03

Carlos


2 Answers

Remember the clash in Java between java.util.Date and java.sql.Date? If someone uses Date in their code, you can't tell whether they forgot import java.util.Date or import java.sql.Date.

In both Java and C++, it is not possible to tell with certainty what import/include statement is missing. So neither language tries. Your IDE might make suggestions for undeclared symbols used in your code.

The problem is further complicated in C++, because the standard says that any standard header can include any other standard header(s). It's therefore very easy to use a function or class without directly including the header which defines it, because your compiler happens to include the right header indirectly. The resulting code works in some implementations but not others, according to whether they share that header dependency.

It's not in general possible for a C++ IDE to tell whether a header dependency is "guaranteed", or just an incidental implementation detail that users shouldn't rely on. Obviously for standard libraries it could just know what's defined in what headers, but as soon as you get to third party libraries it gets quite uncertain.

I think most C++ programmers expect to have to look up what headers define what symbols. With Java, the one-public-class-per-file rule simplifies this considerably, and you just import the packages/classes you want. C++ doesn't have packages, and the only way for the IDE to find a class called my_namespace::something::MyClass is to search for it in every header file.

like image 127
Steve Jessop Avatar answered Sep 29 '22 22:09

Steve Jessop


Why are missing headers not automatically checked and added or requested to the programmer?

But they are automatically checked.

  1. My compiler fails compilation when it can't find a header.
  2. My IDE (eclipse) adds a visual clue when it can't find a header file I've #included, it underlines the #include line and provides a tooltip telling me what the problem is.

It won't automatically add an include because it can't know which include I forgot. Compilers aren't psychic.

like image 23
Glen Avatar answered Sep 29 '22 20:09

Glen