March 28th, 2013, 09:09 AM
Need clarification - header files in C++
Let's say I have a multiple files project:
and so on...
then main.cpp has to contain:
but each of the .h files also has to contain:
doesn't that mean that main.cpp will import these libraries multiple times?
#include<whatever library I need to implement the .cpp files>
Last edited by so.very.tired; March 28th, 2013 at 09:11 AM.
March 28th, 2013, 10:29 AM
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:
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.
int add(int a, int b);
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:
And, of course, iostream.h does the same.
// -*- C++ -*- forwarding header.
// This file is part of the GNU ANSI C++ Library.
March 28th, 2013, 11:21 AM
forgot that iostream.h or any other standard library - much like my header files - also contains the macro #ifndef... :D