Hello,
I'm new to C++ and have a question about where to put #include 's (like #include <iostream>... from std library for example, not my own headers) and staff like "using namespace std": to the source file, or to the header file???
For example, what is considered correct way, 1 or 2:
1.
SomeProg.h
1 2 3 4 5 6 7 8 9 10 11
#ifndef _SomeProg_h_
#define _SomeProg_h_
#include <iostream> // I'm including everything here
#include <fstream>
usingnamespace std;
int SomeFunction(){}
// some function
#endif
SomeProg.cpp
1 2 3 4 5
#include "SomeProg.h" //so I included header here and don't use
// includes before main function
int main(){}
2.
SomeProg.h
1 2 3 4 5 6 7
#ifndef _SomeProg_h_
#define _SomeProg_h_
int SomeFunction(){}
// some function
#endif
SomeProg.cpp
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream> // I'm including everything here
#include <fstream>
usingnamespace std;
/* BTW, if I include all the staff above after the #inlcude "SomeProg.g" line,
compiler gives an error, because it needs those includes to process this header */
#include "SomeProg.h" //so I included header here and don't use
// includes before main function
int main(){}
So, in the case of 2 I should always include standard #includes before I include my header......
I'm a little bit confused here...
Put the includes only in files which actually need the things you're including. If SomeProg.h does not actually have any vectors in it... it should not be including <vector>.
On the other hand... if SomeProg.h does use vectors, then you absolutely should be including <vector> in the header.
A frequent exception to this rule is to have a "common" header file which includes a lump of headers. Something like:
what if the other header file use the same include (for example #include <vector>)??? And both of these files are the parts of the one big program?
Isn't it going to give me compiler error?
For example, let's use your example from the "Headers and Includes" article (great article of yours, btw, thanks a lot!), but with some editing to ask my question:
1 2 3 4 5 6 7 8
//x.h
#ifndef __X_H_INCLUDED__ // if x.h hasn't been included yet...
#define __X_H_INCLUDED__ // #define this so the compiler knows it has been included
class X { };
#endif ;
1 2 3 4 5 6 7 8 9
// a.h
#ifndef __A_H_INCLUDED__
#define __A_H_INCLUDED__
#include "x.h"
#include <vector>
class A { X x; }; //class A uses <vector>
#endif
1 2 3 4 5 6 7 8 9
// b.h
#ifndef __B_H_INCLUDED__
#define __B_H_INCLUDED__
#include "x.h"
#include <vector>
class B { X x; };
#endif//also uses <vector>
1 2 3 4
// main.cpp
#include "a.h" // also includes "x.h"
#include "b.h" // includes x.h again! but it's guarded, so no problem with x.h
So, x.h is guarded, and it's fine. But what about <vector>? It's included two times here.... And we can't guard <vector>, can't we???