views:

43

answers:

3

Not sure if this is a duplicate, please link to similar question if it is.

I have a precompiled header stdafx.h which is used in all source files in my project. Thus all headers in the stdafx.h are available in all code files in the project.

What I'm unsure about is whether or not to re-include stuff thats alrdy in the precompiled header. What do you guys think?

e.g.

stdafx.h

#pragma once

#include <memory>

my_class.h

#pragma once

#include <memory> // Re-include or not that's the question. Best practice?

struct my_class
{
};
typedef std::shared_ptr<my_class> my_class_ptr;

main.cpp

#include "stdafx.h"
#include "my_class.h"

int main()
{
}

EDIT: added pragma once

+2  A: 

I would include it so that the header could be reused in a project which has different stdafx.h Another way of stating this is each header should contain all the declarations (preferably forward ones) it needs on its own

There will not be any performance hit as the contents of the header will not be processed due to internal header guard (or for VS the #pragma:once in the header file.

Mark
Sounds reasonable. The only problem I can see with this is that it could become a bit inconsistent, as you can forget to include all headers. Any suggestions regarding not forgetting to include all headers? Is there any tool or warning setting in VS2010?
ronag
Yes unit tests - include each class in a unit test and the tests won;t ave the same stdafx.h - however will take time to compile. You could also set up VS only to compile and compile on a version with nothing in stdafx.h - do this run or a build with empty stdafx.h at say weekly intervals
Mark
+1  A: 

In a header you should include everything, that is necessary for that header to be used separately. If you use std::shared_ptr in a header and that template comes from memory header, include memory header.

When you design a header your goal should be to make it complete, so that when someone includes it, he/she doesn't get errors caused by unresolved references. Don't worry that some headers might be included repeatedly. There are other mechanisms to protect against that.

BTW, use those mechanisms (like #pragmaor #ifndef/#define) in your header too.

Maciej Hehl
+1  A: 

The best practice would be to use forward declarations as much as possible. Having unnecessary includes might increase compilation time. Always include headers in a file if the implementation uses it even though it was included in a previously included file. This way, if some day you need to remove the header inclusion from the previous file, you will not cause errors in this file and the file won't need any modification.

Elroy