Multiple inclusion of header file c++ - c++

I have a problem regarding multiple inclusion of header file in C++ code.
Say for example, I have three classes X, Y, Z. X and Y are derived from base class Z. And I want to create an instance of X in Y. The code will go like this.
class Z { …some code… };
class X: public Z { …some code… }; //here #include header of class Z added
class Y: public Z //here #include header of class Z added as well as of X class
{
private:
X* mX; //instance of X
…some code…
};
So in this multiple definition of all methods of base class arises. How can I cope with this problem?

Using "include guards" (Wikipedia link)
#ifndef MYHEADER_H
#define MYHEADER_H
// header file contents go here...
#endif // MYHEADER_H
This is idiomatic code, easily recognizable by any seasoned C and C++ programmer. Change MYHEADER_H to something specific to you, for example if the header defines a class named CustomerAccount, you can call the guard CUSTOMERACCOUNT_H.
In your specific case, have a separate header/source file for each class. The header file for the Z class will have an include guard:
#ifndef Z_H
#define Z_H
// Code of Z class
#endif Z_H
Now, the headers of both X and Y can include z.h safely - it will only really be included once in a .cpp file that includes both x.h and y.h and no duplication will occur.
Always keep in mind that in C and C++ what's really gets compiled are the source (.c or .cpp) files, not the header files. The header files are just "copy-pasted" by the preprocessor into the sources files that include them.

You can also use #pragma once preprocessor directive in your header files. (There's no need to bother about #ifndef, #define, #endif).

You use what are called include guards or header guards. They go something like this:
// within some_header.h
#ifndef SOME_HEADER_H
#define SOME_HEADER_H
// stuff goes here
#endif
Essentially, the first time around the macro hasn't been defined so everything inside is included. However, after the first time subsequent includes will have no effect.
The naming scheme, like all naming schemes, is completely arbitrary and up to you. I like to include the file name as a minimum, as I did above, in that fashion. I also include namespaces and project names in my real projects.
There are a couple of things to watch out for. You might be tempted to do things like this:
#define _SOME_HEADER_H__
To obfuscate it a bit. However, names that begin with an underscore followed by a capital letter, or contain double-underscores are reserved identifiers, and you cannot use them.

Here the simple way to avoid multiple header inclusion in the project.
//MYCLASS.h
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
class CMyClass
{
public:
CMyClass();
}
#endif //_MYCLASS_H_

Related

How do I make header files?

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 {};

Header guard in c++ [duplicate]

At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:
add.h:
#include "mymath.h"
int add(int x, int y);
subtract.h:
#include "mymath.h"
int subtract(int x, int y);
main.cpp:
#include "add.h"
#include "subtract.h"
In implementing the header guard, it is mentioned as follows:
#ifndef ADD_H
#define ADD_H
// your declarations here
#endif
What could the declaration be here? And, should int main() come after #endif?
Is adding _H a convention or a must do thing?
Thanks.
The FILENAME_H is a convention. If you really wanted, you could use #ifndef FLUFFY_KITTENS as a header guard (provided it was not defined anywhere else), but that would be a tricky bug if you defined it somewhere else, say as the number of kittens for something or other.
In the header file add.h the declarations are literally between #ifndef and #endif.
#ifndef ADD_H
#define ADD_H
#include "mymath.h"
int add(int x, int y);
#endif
Finally, int main() shouldn't be in a header file. It should always be in a .cpp file.
To clear it up:
#ifndef ADD_H basically means "if ADD_H has not been #defined in the file or in an included file, then compile the code between #ifndef and #endif directives". So if you try to #include "add.h" more than once in a .cpp file, the compiler will see what the ADD_H was already #defined and will ignore the code between #ifndef and #endif. Header guards only prevent a header file from being included multiple times in the same .cpp file. Header guards don't prevent other .cpp files from including the header file. But all .cpp files can include the guarded header file only once.
The result of preprocessing one implementation (".cpp") file is a translation unit (TU).
Headers can include other headers, so a header may be indirectly included multiple times within the same TU. (Your mymath.h is an example of this.)
Definitions can only occur at most once per TU. (Some definitions must also not be in multiple TUs; this case is slightly different and not discussed here.)
The problem include guards solve is preventing multiple definition errors when a given header is included more than once within one TU.
Include guards work by "wrapping" the contents of the header in such a way that the second and subsequent includes are no-ops. The #ifndef/#define directives should be the first two lines of the file, and #endif should be the last.
Include guards are only used in headers. Do not define your main function in a header: put it in an implementation file.
If you have a header that will define a type and declare a function, but also needs a header itself:
#include "other_header.h"
struct Example {};
void f();
"Wrapping" it with include guards gives the complete contents of the file:
#ifndef UNIQUE_NAME_HERE
#define UNIQUE_NAME_HERE
#include "other_header.h"
struct Example {};
void f();
#endif
The name used for the include guard must be unique, otherwise conflicting names will give confusing results. These names are only simple macros, and there is nothing in the language which enforces a certain style. However, project conventions usually impose requirements. There are several different include guard naming styles you can find here on SO and elsewhere; this answer gives good criteria and a good overview.
All the header guards do is to only allow your headers to be included once. (If they're included multiple times, they're ignored.)
The name you use doesn't matter, but it's conventional to use the file name in caps, including the extension like you demonstrated.
Your main should really be in a .cpp file, but if you're putting it in a header, put it inside the guards so it isn't declared multiple times.
No, the int main() goes in a .cpp. The declarations are the other stuff you were gonna put in the header. _H is a convention, you can see various header guard conventions around.
I declare a declaration in header file and definitions or int main() comes in source.cpp file.
_H is there to merely indicate that someone is going to include header files using include guards.
If you're on MSVC++ you can also use #pragma once

Header guards in C++ and C

At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:
add.h:
#include "mymath.h"
int add(int x, int y);
subtract.h:
#include "mymath.h"
int subtract(int x, int y);
main.cpp:
#include "add.h"
#include "subtract.h"
In implementing the header guard, it is mentioned as follows:
#ifndef ADD_H
#define ADD_H
// your declarations here
#endif
What could the declaration be here? And, should int main() come after #endif?
Is adding _H a convention or a must do thing?
Thanks.
The FILENAME_H is a convention. If you really wanted, you could use #ifndef FLUFFY_KITTENS as a header guard (provided it was not defined anywhere else), but that would be a tricky bug if you defined it somewhere else, say as the number of kittens for something or other.
In the header file add.h the declarations are literally between #ifndef and #endif.
#ifndef ADD_H
#define ADD_H
#include "mymath.h"
int add(int x, int y);
#endif
Finally, int main() shouldn't be in a header file. It should always be in a .cpp file.
To clear it up:
#ifndef ADD_H basically means "if ADD_H has not been #defined in the file or in an included file, then compile the code between #ifndef and #endif directives". So if you try to #include "add.h" more than once in a .cpp file, the compiler will see what the ADD_H was already #defined and will ignore the code between #ifndef and #endif. Header guards only prevent a header file from being included multiple times in the same .cpp file. Header guards don't prevent other .cpp files from including the header file. But all .cpp files can include the guarded header file only once.
The result of preprocessing one implementation (".cpp") file is a translation unit (TU).
Headers can include other headers, so a header may be indirectly included multiple times within the same TU. (Your mymath.h is an example of this.)
Definitions can only occur at most once per TU. (Some definitions must also not be in multiple TUs; this case is slightly different and not discussed here.)
The problem include guards solve is preventing multiple definition errors when a given header is included more than once within one TU.
Include guards work by "wrapping" the contents of the header in such a way that the second and subsequent includes are no-ops. The #ifndef/#define directives should be the first two lines of the file, and #endif should be the last.
Include guards are only used in headers. Do not define your main function in a header: put it in an implementation file.
If you have a header that will define a type and declare a function, but also needs a header itself:
#include "other_header.h"
struct Example {};
void f();
"Wrapping" it with include guards gives the complete contents of the file:
#ifndef UNIQUE_NAME_HERE
#define UNIQUE_NAME_HERE
#include "other_header.h"
struct Example {};
void f();
#endif
The name used for the include guard must be unique, otherwise conflicting names will give confusing results. These names are only simple macros, and there is nothing in the language which enforces a certain style. However, project conventions usually impose requirements. There are several different include guard naming styles you can find here on SO and elsewhere; this answer gives good criteria and a good overview.
All the header guards do is to only allow your headers to be included once. (If they're included multiple times, they're ignored.)
The name you use doesn't matter, but it's conventional to use the file name in caps, including the extension like you demonstrated.
Your main should really be in a .cpp file, but if you're putting it in a header, put it inside the guards so it isn't declared multiple times.
No, the int main() goes in a .cpp. The declarations are the other stuff you were gonna put in the header. _H is a convention, you can see various header guard conventions around.
I declare a declaration in header file and definitions or int main() comes in source.cpp file.
_H is there to merely indicate that someone is going to include header files using include guards.
If you're on MSVC++ you can also use #pragma once

Circularly declaring Preprocessor directives? Or defines before includes?

I'm a bit new to C++, so bear with me. I'm trying to figure out where exactly to place my #defines and #includes in my project. I have something like this:
main.h
#include "other.h"
#define MAX_GROUPS 100
struct Cat
{
int something[MAX_GROUPS];
}
In other.h I also need to use MAX_GROUPS, so do I also define MAX_GROUPS in other.h like this:
other.h
#define MAX_GROUPS 100
struct Other
{
int taco[MAX_GROUPS];
}
The problem is that I'm defining a constant more than one place. I want to keep it all together.
Alternatively, do I reinclude main.h?
other.h
#include "main.h"
struct Other
{
int taco[MAX_GROUPS];
}
The problem here I think its that is creates like a circular dependancy thing. main.h includes other.h which includes main.h which includes other.h which includes etc...
What is the best way to setup the defines and includes for a project so that things sorta cascade down to other included files? Is it common practice to simply do all your defines before your includes?
Minimising circular dependencies is very important in maintaining your project. For an extended discussion, see "Large Scale C++ Software Design" by John Lakos.
To avoid the specific problem you are having, define values in one header file, and include that header file in every file that needs it. To avoid problems with multiple definitions, use include guards:
#ifndef HEADER_THING_H
#define HEADER_THING_H
/* Rest of the header file goes here. */
#endif
That way if it is already included, it is harmless.
Because main.h #includes other.h, it doesn't need to #define MAX_GROUPS again. It'll pick up that definition from the inclusion.
Generally, you should put the defines inside whichever header is relevant -- or where it is primarily used. In this case, you should put MAX_GROUPS inside other.h. By including other.h in main.h, the define will also be picked up (as mentioned by jwismar).
For bigger projects, however, you'd be better off creating a header file containing only your manifest constants (defines) and just include that where needed.
You could also protect your constants against redefinition case by case...
#ifndef MAX_GROUPS
#define MAX_GROUPS 100
#endif

Can someone help clarify how header files work?

I've been working with C++ for a good couple of weeks now, but the mechanism behind header files (or the linker I suppose?) confuses the heck out of me. I've gotten in the habit of creating a "main.h" to group my other header files and keep the main.cpp tidy, but sometimes those header files complain about not being able to find a different header file (even though it's declared in the "main.h"). I'm probably not explaining it very well so here's an abridged version of what I'm trying to do:
//main.cpp
#include "main.h"
int main() {
return 0;
}
-
//main.h
#include "player.h"
#include "health.h"
#include "custvector.h"
-
//player.h
#include "main.h"
class Player {
private:
Vector playerPos;
public:
Health playerHealth;
};
-
//custvector.h
struct Vector {
int X;
int Y;
int Z;
};
-
//health.h
class Health {
private:
int curHealth;
int maxHealth;
public:
int getHealth() const;
void setHealth(int inH);
void modHealth(int inHM);
};
I won't include health.cpp because it's a bit lengthy (but does work), it does have #include "health.h".
Anyways, the compiler (Code::Blocks) complains that "player.h" can't find the types 'Health' or 'Vector'. I thought that if I used #include "main.h" into "player.h" it would be able to find the definitions for Health and Vector sense they're included in "main.h". I figured they would they would sort of tunnel their way though (player.h -> main.h -> health.h). But that didn't work too well. Is there some kind of a diagram or video that could clarify how this should be set up? Google wasn't much help (nor my book).
The best way to think of your header files are as an "automated copy-and-paste".
A good way to think about it (although not how this is actually implemented) is that when you compile a C file or C++ file, the preprocessor runs first. Every time it encounters an #include statement, it will actually paste the content of that file instead of the #include statement. This is done until there are no more includes. The final buffer is passed to the compiler.
This introduces several complexities:
First, if A.H includes B.H and B.H includes A.h, you've got a problem. Because every time you want to paste A, you would need B and it would internally have A ! That's a recursion. For this reason, header files use #ifndef, to ensure that the same part is not read multiple times. This is likely happening in your code.
Second, your C compiler reads the file after all the header files have been "flattened", so you need to consider that when reasoning about what is declared before what.
The other answers here have effectively explained the way header files and the preprocessor work. The biggest problem you have is the circular dependencies, which from experience, I know can be a royal pain. Also, when that starts happening, the compiler starts to behave in very odd ways and throw error messages that aren't super helpful. The method I was taught by a C++ guru in college was to start each file (a header file for instance) with
//very beginning of the file
#ifndef HEADER_FILE_H //use a name that is unique though!!
#define HEADER_FILE_H
...
//code goes here
...
#endif
//very end of the file
This uses preprocessor directives to automatically prevent circular dependencies. Basically, I always use an all uppercase version of the file name. custom-vector.h becomes
#ifndef CUSTOM_VECTOR_H
#define CUSTOM_VECTOR_H
This allows you to include files willie-nillie without creating circular dependencies because if a file is included multiple times, its preprocessor variable is already defined, so the preprocessor skips the file. It also makes it easier later on to work with the code because you don't have to sift through your old header files to make sure you haven't already included something. I'll repeat again though, make sure the variable names you use in your #define statements are unique for you otherwise you could run into problems where something doesn't get included properly ;-).
Good luck!
You have a circular dependency. Player includes main.h, but main.h includes player.h. Resolve this by removing one dependency or the other.\
Player.h should include health.h and custvector.h, and at this point, I don't think main.h needs any includes. Eventually it may need player.h.
includes work very simple, they just command preprocessor to add the contents of the file to where include is set. basic idea is to include headers that you depend on. in player.h you should include custvector.h and Health.h. In main only player.h, because all needed includes will be carried with player. and you don't need to include main.h in player.h at all.
it is good also to make sure that header is included only once. in this question general solution is given How to prevent multiple definitions in C? in case of Visual Studio you can use #pragma once, if Borland c++ there is also a trick but i forgot it.
You want to organize your #includes (and libraries, for that matter) in a DAG (directed, acyclic graph). That's the complicated way of saying "avoid cycles between header files":
If B includes A, A should not include B.
So, using "one big master main.h" is not the right approach, because it's hard to #include only direct dependencies.
Each .cpp file should include its own .h file. That .h file should only include things that it itself requires to compile.
There is usually no main.h, because main.cpp nobody needs the definition of main.
Furthermore, you'll want include guards to protect you against multiple includes.
For example
//player.h
#ifndef PLAYER_H_
#define PLAYER_H_
#include "vector.h" // Because we use Vector
#include "health.h" // Because we use Health
class Player {
private:
Vector playerPos;
public:
Health playerHealth;
};
#endif
-
//vector.h
#ifndef VECTOR_H_
#define VECTOR_H_
struct Vector {
int X;
int Y;
int Z;
};
#endif
-
//health.h
#ifndef HEALTH_H_
#define HEALTH_H_
class Health {
private:
int curHealth;
int maxHealth;
public:
int getHealth() const;
void setHealth(int inH);
void modHealth(int inHM);
};
#endif
The only time you want to aggregate a bunch of #includes into a single header is when you're providing it as a convenience for a very large library.
In your current example, you're going a little overboard - each class doesn't need its own header file. It can all go in main.cpp.
The c preprocessor literally inserts the file from a #include into the file that includes it (unless it has already been inserted, which is why you need the include guards). It allows you to use the classes defined in those files because you now have access to their definition.