Including a main.h

I couldn't find the answer to this question as it's kind of a strange one but...

is it a good or bad idea/practice to, for instance, have a main.cpp, with your main function, and a main.h, that would have #include <iostream>, #include <string>, what have you.

Not really either. Generally I would avoid it - it makes more sense to have the include files only in the files that require them. However, some compilers support precompiled headers, so you could have a "main.h" file with common headers between all your files to reduce compilation time.
Both iostream and string are header files. If you write a main.h, it is a header file.

The main.cpp is a source file. You only compile the source files. Before actual compilation, a preprocessor handles directives, such as the #include.

Therefore, if you write main.cpp:
1
2
3
4
5
#include <string>

int main() {
  return 0;
}

The compiler will actually see the contents of string in place of that line 1.

Now, you propose to write a main.h:
1
2
3
4
#ifndef DEC_MAIN_H
#define DEC_MAIN_H
#include <string>
#endif 

That file is of no use, unless you include it:
1
2
3
4
5
#include "main.h"

int main() {
  return 0;
}

What does the preprocessor do now? It does replace line 1 with the content of main.h, which means contents of the string file. In other words: in both cases the compiler sees the same source code, but with the separate main.h the preprocessor does a bit more work.

That does not seem useful in this utterly simple example case. Things change when you have more source files and many of them have to see the same declarations. Then it makes sense to put the shared declarations into a header file and include that in the sources that do need them.


The need is a keyword. The iostream and string are library headers. They probably include many more headers and there are definitely templates, so including them brings in a lot of code. Therefore, you don't want to include any more headers than what is necessary.
Topic archived. No new replies allowed.