3

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
calccrypto
  • 8,583
  • 21
  • 68
  • 99

1 Answers1

9

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.

Community
  • 1
  • 1
GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • the rule "no underscore followed by an capital" applies only at the beginning of the identifier. – Vlad Nov 09 '10 at 00:01
  • 2
    "This almost guarantees it'll never collide" - well, that one doesn't, now you've posted it on the internet ;-) – Steve Jessop Nov 09 '10 at 00:48
  • @Steve: Haha. I stole that one [from Pate](http://stackoverflow.com/questions/1760726/compose-output-streams/1760753#1760753). :) – GManNickG Nov 09 '10 at 01:01
  • 1
    Just for the record - gcc, visual c++ etc. support a "#pragma once" that does the same thing. I'm not recommending it - just mentioning it so readers understand its purpose if they encounter it. – Tony Delroy Nov 09 '10 at 01:37
  • wait... so would the thing that comes after `#ifndef` be the string of the .h file name, or would it be a function from the .h file? – calccrypto Nov 09 '10 at 05:08
  • 1
    @calccrypto: Whatever you want. For my projects, files are named after there contents, and I keep things very distinct; few files, if any, have more than one function or class. So your question, for me, is "yes". :) I also put them into a namespace that matches the folder they're in. So the file `./utility/blah.hpp` contains a function (or class) akin to `namespace utility { void blah(); }`, with the guard `UTILITY_BLAH_HPP`. If it's intended to be used outside my own work, I'd prefix it with a project name as well. – GManNickG Nov 09 '10 at 05:54