Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i include multiple class with the same includes?

Tags:

c++

include

class

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
like image 494
calccrypto Avatar asked Jan 24 '26 07:01

calccrypto


1 Answers

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.

like image 180
GManNickG Avatar answered Jan 26 '26 20:01

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!