#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    132
    Rep Power
    2

    Need clarification - header files in C++


    Hi guys.

    Let's say I have a multiple files project:
    main.cpp
    classA.cpp
    classA.h
    classB.cpp
    classB.h
    classB.cpp
    classB.h
    and so on...

    then main.cpp has to contain:
    Code:
    #include"classA.h"
    #include"classB.h"
    #include"classC.h"
    ...
    but each of the .h files also has to contain:
    Code:
    #include<iostream>
    #include<string>
    #include<whatever library I need to implement the .cpp files>
    ...
    doesn't that mean that main.cpp will import these libraries multiple times?
    Last edited by so.very.tired; March 28th, 2013 at 09:11 AM.
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    No, not if they were written correctly.

    When you write a header file, use a guard define. It's discussed and a short example is given in Wikipedia's Header file article:
    Code:
    #ifndef ADD_H_GUARD
    #define ADD_H_GUARD
    int add(int a, int b);
    #endif
    As you can see, the contents of the file will only be used if the macro ADD_H_GUARD has been defined and the first thing the header file does is to #define ADD_H_GUARD. So the first time this header file is included, the ADD_H_GUARD is not defined so the contents are used, a side-effect of which is that ADD_H_GUARD gets defined. Then every other time that the header file gets included in the same compilation (remember that each source file is compiled separately as a separate compilation), ADD_H_GUARD is already defined so the contents of the header file are ignored. End result: no duplicate declarations in the header files.

    Wikipedia calls guard defines "include guards". An alternative is to use the pragma once directive.

    The standard library header files use guard defines. For example, here's the contents of iostream in MinGW gcc:
    Code:
    // -*- C++ -*- forwarding header.
    // This file is part of the GNU ANSI C++ Library.
    
    #ifndef __IOSTREAM__
    #define __IOSTREAM__
    #include <iostream.h>
    #endif
    And, of course, iostream.h does the same.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    132
    Rep Power
    2
    Thanks dwise1_aol.

    forgot that iostream.h or any other standard library - much like my header files - also contains the macro #ifndef... :D

IMN logo majestic logo threadwatch logo seochat tools logo