how do i include multiple class with the same includes? - c++

How do i include two .h/class files that both have #include "h_file.h"? both require the .h file definitions, and both are included in the main program. how do i prevent the redefinition of the .h definitions (which causes the compiler to not compile)?
i have:
main.cpp
class1.h/class1.cpp
class2.h/class2.cpp
h_file.h

Use include guards:
#ifndef INCLUDE_GUARD_IDENTIFIER_GOES_HERE
#define INCLUDE_GUARD_IDENTIFIER_GOES_HERE
// code for header
#endif
The second time it's included, it's effectively an empty file.
There are many different ways of choosing the identifier INCLUDE_GUARD_IDENTIFIER_GOES_HERE, with rationales for each. Personally, I do FILE_DIRECTORY_FILE_NAME_CLASS/FUNCTION_NAME_HPP:
#ifndef UTILITY_FOO_HPP
#define UTILITY_FOO_HPP
namespace utility
{
void foo();
}
#endif
Others will generate GUID's and attach them to a base name, like this:
INCLUDE_GUARD_A629F54A136C49C9938CB33EF8EDE676
This almost guarantees it'll never collide. Ultimately, it's up to you. However, regardless of what you come up with, make sure it follows the rules: No double underscores anywhere, and don't start it with an underscore followed by an upper-case letter.

Related

Can/should I type whatever I want after #ifndef?

Example:
#ifndef HEADER_h
#define HEADER_h
#endif
Instead of HEADER_h, can I do the following?
#ifndef HEADER
or
#ifndef LIBRARY
or
#ifndef SOMETHING
or
#ifndef ANOTHERTHING
etc.
Header guards are just a convention, a "trick", making use of preprocessor conditions. In using a header guard you are creating a macro with a name, and checking whether that macro was already defined.
There is nothing magical about this macro that binds it to the filename of a header, and as such you can call it whatever you want (within reason).
That doesn't mean that you should write #ifndef URGLEBURGLE, though. You want the name to be useful and unique, otherwise there's not much point.
Typically something like #ifndef [PROJECTNAME]_[FILENAME]_INCLUDED is a good idea.
Yes, you can name the include guard symbol whatever you want, but bear in mind that they are supposed to be unique across headers. You definitely don't want a header
// first.h
#ifndef NON_UNIQUE_H
#define NON_UNIQUE_H
void foo();
#endif
and another one
// second.h
#ifndef NON_UNIQUE_H
#define NON_UNIQUE_H
void bar();
#endif
When you include both in one translation unit, one will "win" and its declarations will be visible, e.g.
// main.cpp
#include "first.h" // now, NON_UNIQUE_H is defined
#include "second.h" // NON_UNIQUE_H already there, doesn't do anything
int main(int, char**)
{
bar(); // error, won't compile, bar() isn't declared
}
Besides the necessity to circumvent such scenarios, it's best to stick to some convention throughout your project. One classical way of doing it is to convert the header file base name to upper case and append _H. If you have header files with the same base name in different directories, you can include the directory name, e.g. SUBDIR_FOO_H and OTHERSUBDIR_FOO_H. But this is up to you.
You can use a construction like
#if !defined(HEADER) || !defined(LIBRARY)
At your question, you are using
#ifndef HEADER_h
#define HEADER_h
#endif
It's the same as "#pragma once"
And yes, you can use different names of defines. In your case, LIBRARY, SOMETHING, HEADER_h - defines, that you can set in code(#define MY_VAR_NAME) or via compiler options(flag -DMY_VAR_NAME).
Your example is a so-called header guard that allows us to ensure the contents of the header are included only once. However, that is not the only use of #ifndef.You can use #ifndef for conditional compilation as in
#ifndef NO_DEBUG
do_some_debug_stuff();
#endif
So it is not only for header guards, but in general you have to carefully choose the name of the symbols you are introducing to prevent they are clashing with symbols defined elsewhere. It is just that header guards are so common that certain conventions exist (eg using FOLDER_FILENAME_H is usually sufficient to ensure uniqueness). And you need to be aware that certain names are reserved (eg starting with two underscores or underscore followed by capital letter).

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

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.

Preprocessor directive #ifndef for C/C++ code

In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:
/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif
I think ifndef is saying that if EXAMPLE_H_ isn't defined, define it, which may be useful depending on what tool you are using to compile and link your project. However, I have two questions:
Is this fairly common? I don't see it too often. And is it a good idea to use that rubric, or should you just jump right into defining your code.
What is EXAMPLE_H_ exactly? Why not example.h, or just example? Is there anything special about that, or could is just be an artifact of how eclipse prefers to auto-build projects?
This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.
Putting the #ifndef wrapper around the contents means the compiler only parses the header's contents once, and avoids redefinition errors.
Some compilers allow "#pragma once" to do the same thing, but the #ifndef construct works everywhere.
This is just a common way to protect your includes - in this way it prevents the code from being included twice. And the identifier used could be anything, it's just convention to do it the way described.
Is it common? Yes - all C and C++ header files should be structured like this. EXAMPLE_H is a header guard, it prevents the code in the header being included more than once in the same translation unit, which would result in multiple definition errors. The name EXAPMLE_H is chosen to match the name of the header file it is guarding - it needs to be unique in your project and maybe globally as well. To try to ensure this, it's normal to prefix or suffix it with your project name:
#define MYPROJ_EXAMPLE_H
for example, if your project is called "myproj". Don't be tempted into thinking that prefixing with underscores will magically make it unique, by the way - names like _EXAMPLE_H_ and __EXAMPLE_H__ are illegal as they are reserved for the language implementation.
Always do this at the top of a header file. It's typically called a header guard or an include guard.
What it does is make it so that if a header file would be included multiple times, it will only be included once. If you don't do it, then you'll end up with errors about things being defined multiple times and things like that.
The exact define doesn't matter that much, though typically it's some variation on the file name. Basically, you're checking whether the given macro has been defined. If it hasn't, then define it, and continue with including the file. If it has, then you must have included the file previously, and the rest of the file is ignored.
This is an include guard. It guarantees that a header is included no more than once.
For example, if you were to:
#include "example.h"
#include "example.h"
The first time the header is included, EXAMPLE_H_ would not be defined and the if-block would be entered. EXAMPLE_H_ is then defined by the #define directive, and the contents of the header are evaluated.
The second time the header is included, EXAMPLE_H_ is already defined, so the if-block is not re-entered.
This is essential to help ensure that you do not violate the one definition rule. If you define a class in a header that didn't have include guards and included that header twice, you would get compilation errors due to violating the one definition rule (the class would be defined twice).
While the example above is trivial and you can easily see that you include example.h twice, frequently headers include other headers and it's not so obvious.
Consider this
File foo.c:
#include foo.h
#include bar.h
File bar.h
#include <iostream>
#include foo.h
Now, when we compile foo.c, we have foo.h in there twice! We definitely don't want this, because all the functions will throw compile errors the second time around.
To prevent this, we put the INCLUDE GUARD at the top. That way, if it's already been included, we define a preprocessor variable to tell us not to include it again.
It's very common (often mandated), and very frustrating if someone doesn't put one in there. You should be able to simply expect that each .h file has a header guard when you included. Of course, you know what they say when you assume things ("makes an ass of u and me") but that should be something you're expecting to see.
This is called an include guard and is indeed a common idiom for C/C++ header files. This allows the header file to be included multiple times without multiply including its contents.
The name EXAMPLE_H_ is an arbitrary convention but has to obey naming rules for C preprocessor macros, which excludes names like example.h. Since C macros are all defined in a single global namespace, it is important that you do not have different header files that use the same name for their include guard. Therefore, it is usually a good idea to include the name of your project or library in the include guard name:
#ifndef __MYPROJECT_EXAMPLE_H__
...