Does C++ include all headers a included header file includes?

Viewed 853

In this example code, I have 3 files:

testHeader.h:

void hello() {  }

file1.h:

#include "testHeader.h"
#include <iostream>
void sayHi() { std::cout << "hi" << std::endl; }

file2.h:

#include "file1.h"
void sayHello() { std::cout << "hello" << std::endl; }

If file1.h includes testHeader.h and file2.h includes file1.h, do testHeader.h and its functions become accessible in file2.h? What about <iostream> and its functions?

2 Answers

Unless protected by preprocessor guards in weird ways, yes, you get them all. #include is largely a preprocessor trick, roughly equivalent to dumping the text of the include into the source code, and it's transitive; if you #include <a.h>, you get the expanded form of a.h, including the preprocessor expanded form of all its includes, all their includes, etc., etc. ad infinitum, in a single pass.

Note that it's still a good idea to explicitly include all the things you rely on directly; sure, the other .h files might #include <vector> today, but that's no guarantee the next release will have them if they're not a necessary part of the API being exposed.

It's also worth noting that preprocessor include guards (and/or #pragma once) is used almost universally to mean a .h file's contents don't get included twice (by convention, not a guarantee; in the case of poorly written .h files, or weird ones designed for multiple inclusion with different preprocessor setups it won't be obeyed); there is little to no cost to re-including a header in the .cpp that it already got from a .h you included. On older compilers, without #pragma once and with no special handling for include guards, it might have to load the header a second time, see the guard, and dump nothing on the second include; many newer compilers are smart enough to avoid even that cost. Point is, don't try to optimize by avoiding redundant #includes; every file should have the complete set of #includes needed for the things used in that file, no more, no less.

If you work on older compilers, without #pragma once, then try to do as following.

--- file1.h ---

#ifndef FILE1_H
#define FILE1_H

#include "testHeader.h"
#include <iostream>
void sayHi();

#endif

--- file1.cpp ---

#include "file.h"
void sayHi() { std::cout << "hi" << std::endl; }

--- file2.h ---

#ifndef FILE2_H
#define FILE2_H

#include "file1.h"
#include <iostream>
void sayHello();

#endif

You shouldn't make a body of function in HEADER file. It might cause a compile error for multiple links for the same function. Please write function' prototype and body into Header and Source file seperately.

Related