Should re-include stuff thats already in the project scope precompiled header?

落爺英雄遲暮 提交于 2020-01-25 00:30:06

问题


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 already 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()
{
}

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3691077/should-re-include-stuff-thats-already-in-the-project-scope-precompiled-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!