Tom N Tom N - 3 months ago 18
C++ Question

C++ Library Inclusion Guards

Just a question of style, or possibly even a malpractice I am unaware of.

I am currently writing my first piece of software, which will be used and reviewed by people other than myself. When I am writing my code and calling my headers, is it bad practice to call the same header multiple times across files.

For example

exampleClass.h

#ifndef BUG_H
#define BUG_H
#include<string>

class Bug{
private:
int bug_id; //6 digit int
Date creation_ts; //Date object containing time of creation
std::string short_desc; //Short description of bug
std::string classification; //Catagory of bug_id
std::string product; //What product is the bug regarding
std::string component
}

#endif


anotherExample.h

#ifndef ANOTHEREXAMPLE_H
#define ANOTHEREXAMPLE_H
#include<string>

class Pug{
private:
int bug_id; //6 digit int
Date creation_ts; //Date object containing time of creation
std::string short_desc; //Short description of bug
std::string classification; //Catagory of bug_id
std::string product; //What product is the bug regarding
std::string component
}

#endif


Is there anything wrong with including string twice in two different header files if both have dependencies? Will this cause errors later in the software's life?

Answer

If the two files are unrelated, eg not included both in the same source, then you have no choice. Otherwise, It doesn't really matter, since <string> would get included anyway, if you included one file after the other. One of the files would still need it. But still, if one file ever needs a file, ALWAYS include it. There is always the risk that one time someone may forget to include the other file, and the code won't compile. Don't take the risk, trusting clients.

In addition, std::string has include guards as well, so no need to worry about multiple inclusion. Also, for safety of inclusion, you can do this fr your headers:

#pragma once
#ifndef HEADER_H
#define HEADER_H
//.....Code
#endif

You could always #pragma or #define, (as in 1 or the other), but putting both guarantees header guards, since old compilers don't support #pragma once

Comments