I never knew that headers included in a source file are visible to other headers which are also included. |
They don't. Kind of.
When you compile your main.cpp, a
preprocessor processes it first. It executes the directives like
#include.
You had main.cpp:
1 2 3 4 5 6 7
|
#include <GL/glew.h>
#include <SDL.h>
#include "shader_library.hpp"
#include "shader_loader.hpp"
// code of main
|
That converts to:
1 2 3 4 5
|
// contents of GL/glew.h
// contents of SDL.h
// contents of shader_library.hpp
// contents of shader_loader.hpp
// code of main
|
But wait! The shader_loader.hpp has an #include. No worries, preprocessor is recursive:
1 2 3 4 5 6
|
// contents of GL/glew.h (1)
// contents of SDL.h
// contents of shader_library.hpp
// contents of GL/glew.h (2)
// rest of contents of shader_loader.hpp
// code of main
|
Oh no, we got some code twice! That is surely an error?
Yes it is, but no we didn't. Each header should have
inclusion guards that stop the preprocessor copying their contents more than once into the same translation unit. The glew.h is a good header and that is why its second inclusion adds nothing.
When the preprocessor has finished, the compiler gets the resulting text.
Order is important. You have to declare first, before use.
Herb Sutter has written many times on his Guru of the Week series about include's dos and don'ts.