Thing not totally clear to me redarding headers

Hello people,

Is it better to put all the header files I use throughout my program in a custom header file with a #pragma once directive before the includes, and include this file in every source file, than including headers in every source file? If yes, why?

Also... Is it ok to use headers only for forward declarations of functions and having the declaration in a source file or is it also ok to have the whole function in the header?

Thank you for your answers!
Last edited on
For the first one, no, that's a bad idea. That will massively and unnecessarily increase compile times because you are including lots of things that you don't need, and when one thing is changed, loads of things have to be recompiled. As for the second question, headers normally contain declarations of classes and functions, with source files containing the definition.
Thank you for your answer. Now... How can i tell the compiler not to re-include a header used twice in the program? It was never clear how should I use ifndef ... guard macro or #pragma once. (I am not worried about portability). And if #pragma once is seen by the compiler while compiling a header, shouldn't the compiler skip compiling the same header twice?
Last edited on
If I have a file called MyHeader.h, it looks like this:
1
2
3
4
#ifndef MYHEADER_H
#define MYHEADER_H
// Rest of header file
#endif 

I went so far as to create a shell script at work that creates this stub (plus a copyright notice).
Is it better to put all the header files I use throughout my program in a custom header file with a #pragma once directive before the includes, and include this file in every source file, than including headers in every source file? If yes, why?

The only time it makes sense to do this is when you're using pre-compiled headers.


should I use ifndef ... guard macro or #pragma once. (I am not worried about portability)
#pragma once is not standard, but it is surprisingly portable.


And if #pragma once is seen by the compiler while compiling a header, shouldn't the compiler skip compiling the same header twice?

Headers aren't compiled, per se. They are essentially copy/pasted into your source file prior to compilation. Assuming #pragma once is supported by your compiler, it will keep the contents from being pasted in twice.
Topic archived. No new replies allowed.