include files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madshov
    New Member
    • Feb 2008
    • 20

    include files

    Hi,
    I would like to hear opinions of the best way to include files (classes) within each other, without getting previously defined errors. Anyone have good tips for doing this?
  • IanWright
    New Member
    • Jan 2008
    • 179

    #2
    Originally posted by madshov
    Hi,
    I would like to hear opinions of the best way to include files (classes) within each other, without getting previously defined errors. Anyone have good tips for doing this?
    Everything I have read suggests using defines like:

    [CODE=cpp]#ifndef MyClass
    #define MyClass

    class MyClass
    {

    }
    #endif MyClass[/CODE]

    That way you ensure it only ever gets included just once

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Yes and no.

      When you #ifndef MyClass, you are banking on MyClass being a unique name. If it's not and is already defined from some other include, then this header won't be included at all.

      You need to #ifndef a unique symbol.

      The most commonly used thing is a variation on the include file name. Since all headers included in a single build have to have unique names, you can use the header file name. I usually see things like:

      [code=cpp]
      //MyClass.h

      #ifndef _MYCLASSH_
      #define _MYCLASSH_

      //etc...

      #endif
      [/code]

      The underscores are meant to separate your symbols from the user application symbols.

      If you are packaging each class in its own header file and .cpp file, then you have a reasonable convention.

      Comment

      Working...