I get roughly what it does. What I don't understand is why it's not the default? What are the use cases where some header file would need to be included multiple times?
The reason it's not the default is primarily historical these days -- when the C language was formalized, #include was specified that it must act exactly as if the user had copy-and-pasted the specified file's contents at the location of the #include-line; and C++ wanted (and wants) to remain as compatible as possible with C, so C++ inherited that behavior from C.
As for a use-case where including the same header file more than once might be useful; one instance where I found it useful was for simulating a templated-container-class in C (because C doesn't support templates directly). I had a container-implementation-header-file that looked something like this (but more elaborate; I'm showing a simplified version here for readability):
// MyContainerImplemention.h
// be sure to #define MYTYPE and MYARRAYSIZE
// before #include-ing this file!
struct ArrayOf##MYTYPE
{
MYTYPE arrayOfItems[MYARRAYSIZE];
};
inline void Set##MYTYPE##Item(struct ArrayOf##MyType * container, int which, MYTYPE item)
{
container[which] = item;
}
[... and so on for various other MYTYPE-specific methods ...]
... then my .c files could do something like:
#define MYTYPE int
#define MYARRAYSIZE 10
#include "MyContainerImplementation.h"
#undef MYARRAYSIZE
#undef MYTYPE
#define MYTYPE short
#define MYARRAYSIZE 15
#include "MyContainerImplementation.h"
#undef MYARRAYSIZE
#undef MYTYPE
struct ArrayOfint myInts;
struct ArrayOfshort myShorts;
SetintItem(&myInts, 5, 12);
SetshortItem(&myShorts, 3, 2);
[...]
... and end up with the container "class" and its associated methods implemented for each data-type, without having to manually write a new implementation of the container "class" each time.
Yes, it was extremely ugly -- but not as ugly as having to manually write out thousands of lines of redundant container-code would have been. (The real container-implementation-header-file implemented a hash table and was several hundred lines long)
Without include guards or #pragma once the compiler would have to maintain a list of included files. This is not easy, because of different possible paths to these files (and #pragma once doesn't completely solve this) and would be expecting a bit much of the original C compilers, which had to work with very limited memory.
What's true today is not necessarily true when C came about and the C pre-processor, upon which the C++ one is based, was created.
#pragma once is just a step towards having proper C++ modules so this annoying historical legacy is finally eliminated.
Yes, it's valid to include a file multiple times, and yes, each time it's included it can behave in entirely different ways. This is why making pre-compiled headers is a huge headache for compiler developers.
Guard blocks or #pragma once are included in order to prevent a file from being included multiple times.
#pragma once, while supported on most compilers, is not an official part of the c++ standard, and may not work on every compiler. You can use a guard block, which will work on any compiler. An example of a guard block in the file MyClass.hpp would be:
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
//Code here
#endif
Related
I`ve studied C, and now I decided to switch to C++.
So, in C, I used #ifndef #endif in my header files. Should I use the same commands in C++? Or are there some alternatives?
Yes, the preprocessor works (mostly) the same way, so you should still use preprocessor directives to guard against including the same code more than once.
Any differences in functionality between the preprocessor in C and C++ are likely to be edge cases that are unlikely to be relevant at your current learning level.
The file/header relationship is identical in C and C++.
foo.h:
#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE
// your declarations (and certain types of definitions) here
#endif
The C++ preprocessor is essential the same when compared to it’s C counterpart. All directives will work in either language whether written in a header (.h) or a source file (.c, .cc, .cpp).
Read more about the wonders of headers here!
The answer from Commader_Quazar is right and enough.
ALternatively you can substitute:
#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE
// your declarations (and certain types of definitions) here
#endif
with:
#pragma once
// your declarations (and certain types of definitions) here
which lets you write 1 line of code instead of 3, and is less error prone (since in this case you don't have to worry about remembering to put #endif at the end of the file) however I personally prefer the first option.
I have gotten to a point in my course where they use Code::Blocks to automatically make a header file. However, I don't think it's necessary to download Code::Blocks specifically for this reason, and so I am looking for a way to make my own header files.
And so, I started my search online to find out exactly how to do this.
I checked How to create my own header file in c++? [closed] and also cplusplus.com
However, the former uses uses #ifndef YOUR_NAME_INCLUDE and #define YOUR_NAME_INCLUDE whereas the latter uses #ifndef __X_H_INCLUDED__ and #define __X_H_INCLUDED__, with 2 underscores surrounding the #ifndef and #define. How should I format my header guards? Does it really matter?
For example, if I have a file foo.h, which looks like this:
#ifndef ???
#define ???
int sum(int a, int b) {
return a + b;
}
#endif
should I put SUM_INCLUDED, FOO_INCLUDED, FOO_H instead of the ??? or something else altogether?
Second, is making a header file really as easy as just sticking a .h or .hpp to the end of it?
#ifndef FOO
#define FOO
struct foo {};
#endif
The above canonical example ensures that the contents (between #ifndef FOO and #define FOO) are compiled only once allowing us to include this file (say foo.h) in multiple compilation units without causing struct foo to be multiply defined.
There really isn't any "magic" about an include file other than this. In fact, the extension doesn't even matter. It could be foo.h or foo.hh or just foo (like the standard library headers like vector or iostream).
Ultimately, it's personal preference how you structure your include guards. Some use __FOO__ (note this runs afoul of C++ standard regarding reserved identifiers) or FOO_H_INCLUDED (which is standard compliant) while others may elect for different patterns.
While it's not strictly standard C++, my team uses #pragma once and foregoes the ifndef/define/endif code. It's supported by all the compilers we use (gcc/msvc/clang) and you don't have drawbacks such as too different foo.h files causing one (or the other) definition to be excluded.
The same file then looks like this
#pragma once
struct foo {};
I was wondering if there is an elegant way to solve this problem. Suppose there's a common header eg
// common.h
#ifndef COMMON_H
#define COMMON_H
#define ENABLE_SOMETHING
//#define ENABLE_SOMETHING_ELSE
#define ENABLE_WHATEVER
// many others
#endif
Now this file is included by, let's say 100 other header files and the various #define are used to enable or disable some parts of code which are confined to just 1-2 files.
Everytime a single #define is changed the whole project seems to be rebuilt (I'm working on Xcode 5.1), which makes sense as it must be literally replaced all around the code and the compiler can't know a priori where it's used.
I'm trying to find a better way to manage this, to avoid long compilation times, as these defines are indeed changed many times. Splitting each define in their corresponding file/files could be a solution but I'd like the practical way to have everything packed together.
So I was wondering if there is a pattern which is usually used to solve this problem, I was thinking about having
// common.h
class Enables
{
static const bool feature;
};
// common..cpp
bool Enables::feature = false;
Will this be semantically equivalent when compiling optimized binary? (eg. code inside false enables will totally disappear).
You have two distinct problems here:
Splitting each define in their corresponding file/files could be a solution but I'd like the practical way to have everything packed together.
This is your first problem. If I undestand correctly, if you have more than one functional area, you are not interested in having to include a header for each of them (but a single header for everything).
Apply these steps:
do split the code by functionality, into different headers; Each header should contain (at most) what was enabled by a single #define FEATURESET (and be completely agnostic to the existence of the FEATURESET macro).
ensure each header is only compiled once (add #pragma once at the beginning of each feature header file)
add a convenience header file that performs #if or #ifdef based on your defined features, and includes the feature files as required:
// parsers.h
// this shouldn't be here: #pragma once
#ifdef PARSEQUUX_SAFE
#include <QuuxSafe.h>
#elif defined PARSEQUUX_FAST
#include <QuuxFast.h>
#else
#include <QuuxSafe.h>
#endif
// eventually configure static/global class factory here
// see explanation below for mentions of class factory
Client code:
#include <parsers.h> // use default Quux parser
#define PARSEQUUX_SAFE
#include <parsers.h> // use safe (but slower) Quux parser
So I was wondering if there is a pattern which is usually used to solve this problem
This is your second problem.
The canonical way to enable functionality by feature in C++, is to define feature API, in terms of base classes, class factories and programming to a generic interface.
// common.h
#pragma once
#include <Quux.h> // base Quux class
struct QuuxFactory
{
enum QuuxType { Simple, Feathered };
static std::unique_ptr<Quux> CreateQuux(int arg);
static QuuxType type;
};
// common.cpp:
#include <common.h>
#include <SimpleQuux.h> // SimpleQuux: public Quux
#include <FeatheredQuux.h> // FeatheredQuux: public Quux
std::unique_ptr<Quux> QuuxFactory::CreateQuux(int arg)
{
switch(type) {
case Simple:
return std::unique_ptr<Quux>{new SimpleQuux{arg}};
case Feathered:
return std::unique_ptr<Quux>{new FeatheredQuux{arg}};
};
// TODO: handle errors
}
Client code:
// configure behavior:
QuuxFactory::type = QuuxFactory::FeatheredQuux;
// ...
auto quux = QuuxFactory::CreateQuux(10); // creates a FeatheredQuux in this case
This has the following advantages:
it is straightforward and uses no macros
it is reusable
it provides an adequate level of abstraction
it uses no macros (as in "at all")
the actual implementations of the hypothetical Quux functionality are only included in one file (as an implementation detail, compiled only once). You can include common.h wherever you want and it will not include SimpleQuux.h and FeatheredQuux.h at all.
As a generic guideline, you should write your code, such that it requires no macros to run. If you do, you will find that any macros you want to add over it, are trivial to add. If instead you rely on macros from the start to define your API, the code will be unusable (or close to unusable) without them.
There is a way to split defines but still use one central configuration header.
main_config.h (it must not have an include guard or #pragma once, because that would cause strange results if main_config.h is included more than once in one compilation unit):
#ifdef USES_SOMETHING
#include "something_config.h"
#endif
#ifdef USES_WHATEVER
#include "whatever_config.h"
#endif
something_config.h (must not have include guards for the same reason as main_config.h):
#define ENABLE_SOMETHING
All source and header files would #include only main_config.h, but before the include they must declare what part of it would they be referring to:
some_source.cpp:
#define USES_SOMETHING
#include "main_config.h"
some_other_file.h:
#define USES_WHATEVER
#include "main_config.h"
I have seen this countless of times. Instead of
#ifndef _common_h_
#define _common_h_
#endif /* _common_h_ */
people sometimes define their header files in following format:
#ifndef _common_h__479124197491641974591
#define _common_h__479124197491641974591
#endif /* _common_h__479124197491641974591 */
What is that random number good for? I just couldn't successfully google any answer to this.
The idea is to make it harder to trip your include guard unintentionally, and/or to avoid triggering someone elses' include guards.
For example, if you are writing a library, and you have a Common.h header, then using _common_h_ for the guard could prevent users of your library from having _common_h_ guards in their own libraries, which is not ideal. Adding a random number makes such collisions nearly impossible.
The problem
Include guards are often declared in the form:
#ifndef X
#define X
...
#endif
The programmer is free to choose, what we will call here as, a "name". This name is often unique within a single library, but it can happen (even if rare) that two libraries define the same name. This can potentially lead to terrible headaches.
The random numbers
Since the name is often not important outside of the specific file, we can choose (or other tools can do it for us) to include a random number within the name, which will make it much harder to cause name clashes.
#pragma once
You can avoid the problem in another way, by using:
#pragma once
This is a well supported extension, which is compatible with clang, gcc and mvc, as well as many other compilers.
Being pretty new to C++, I don't quite understand some instructions I encounter such as:
#ifndef BOT_H_
#define BOT_H_
#include "State.h"
/*
This struct represents your bot in the game of Ants
*/
struct Bot
{
State state;
Bot();
void playGame(); //plays a single game of Ants
void makeMoves(); //makes moves for a single turn
void endTurn(); //indicates to the engine that it has made its moves
};
#endif //BOT_H_
What I don't understand is the "#ifndef BOT_H_" and the "#define -- #endif"
From what I gather, it defines a constant BOT_H_ if it's not already defined when the precompiler looks at it. I don't actually get how the struct inside it is a constant and how it is going to let me access the functions inside it.
I also don't see why we're doing it this way? I used C++ a while back and I wasn't using .h files, so it might be something easy I'm missing.
This is known as an include guard, to prevent the contents of a header file from being #included more than once.
That is, it prevents the contents of the header file from being copied into the file that #includes it when it has already #included it before.
The #define isn't defining a constant for the struct, but it's simply defining a constant with no value. If that constant was previously defined, the struct will not be redeclared.
It's called "include guard". It protects you from redefinitions occuring when a header is included more than once. There's also non-standard #pragma once that does the same thing, but might not be supported everywhere.
It does not define a constant whose value is the struct. It defines a constant with an empty value.
It's there so that the content of the header is not included twice. Basically it says something like:
if (!bot_h_included)
{
bot_h_included = true;
// code from the header
}
this is called a header guard it stops the compiler compiling or including the code more than once it is similar to pragma once
Just a side note, I don't recommend using #pragma once I see it a lot in a MVC compatible compilers but just a couple of weeks ago I was working with HP UX and the HP-CC does not support #pragma once, I strongly recommend using #ifndef/#define combinations.