C and C++ use a special component in their compilers called a preprocessor. It’s basically a fancy copy-paste machine.
Firstly a breakdown of what all the different preprocessor words mean (you can skip this if you’re sure you know how they work).
#define defines a word to mean something else.
#define FIVE 5 would result in all instances of
FIVE being replaced with
#if tests if a condition is true.
#else provides an alternative case for an
#if, in case it is not true.
#endif ends an
#if VERSION > 5
#ifdef tests if a word is defined and
#ifndef does the opposite - it tests if a word has not been defined.
// This is used
// This isn't
So now that’s out of the way, let’s examine this.
// lots of bitmaps
The correct name for this sequence is a “include guard”.
This says ‘if BITMAPS_H isn’t defined, define it, then look at this C++ code’ which implicitly means ‘if BITMAPS_H is defined, ignore all this code’.
What this results in is a block of code that can only be examined once. This is done for a good reason - trying to read certain bits of code twice will upset the compiler because it will think you are trying to redefine something you have already stated.
The compiler doesn’t realise it’s the same file and doesn’t know to ignore it unless you use that special define sequence.
If your wondering why the compiler might try to read it twice, that’s because of how
#include is basically a copy-paste.
#include "file.h" says 'copy the contents of
file.h and paste it all here. This means that if
#included more than once, you’ll have duplicate sets of code, which is why you need the include guards - to make sure the compiler ignores the duplicates.
As you’ve pointed out, there are two kinds of includes, and they both have different behaviour. The difference is where the preprocessor looks for the file.
If you use the quote syntax
#include "bitmaps.h" then the preprocessor will look for the file locally. E.g. if you had a file “Project/Main.h” and it had a line
#include "Other.h", the preprocessor would look for “Project/Other.h”.
The angle bracket syntax on the other hand, looks for the file in a specially designated library folder and it typically used for external libraries.
What this means is that for files local to your project you want to use the quote-style
#include "bitmaps.h" and for external librarys you want to use angle-bracket-style, like when you
I hope that all makes sense.
There are a few details I’ve left out like
#if defined(WORD) and
#pragma once, but you don’t need to know about those unless you’re really curious.