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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With