在预编译头文件中包含头文件并在我的类头文件中包含头文件

Mr_*_*ags 5 c++ include precompiled-headers

我对此进行了一段时间的搜索,但我不断得到的答案无法回答这个特定的场景。

我有一堂课叫VisibleGameObject. 我想知道如果我将正常的包含放在标头中(以便其他开发人员可以使用相同的类),并将相同的包含放在我的预编译标头中,会发生什么stdafx.h 我不希望开发人员依赖于我的 pch。

// VisibleGameObject.h

#pragma once
#include "SFML\Graphics.hpp"
#include <string>

class VisibleGameObject
{
public:
    VisibleGameObject();
    virtual ~VisibleGameObject();

    virtual void Load( std::string filename );
    virtual void Draw( sf::RenderWindow & window );

    virtual void SetPosition( float x, float y );

private:
    sf::Sprite  _sprite;
    sf::Image _image;
    std::string _filename;
    bool _isLoaded;
};
Run Code Online (Sandbox Code Playgroud)

实施:

// VisibleGameObject.cpp
#include "stdafx.h"
#include "VisibleGameObject.h"

...
Run Code Online (Sandbox Code Playgroud)

个人计算机信息中心:

// stdafx.h
#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>


// TODO: reference additional headers your program requires here
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
Run Code Online (Sandbox Code Playgroud)

当我构建项目时(编译一次后),#include <SFML/Graphics.hpp>每次都会重新编译吗?因为它包含在这个类的头文件中。我认为发生的情况是 pch 首先包含在 cpp 文件的翻译单元中,然后#include <SFML/Graphics.hpp>受到包含保护,因此 pch 正常工作并且我的包含被忽略。在 Visual Studio 中,不首先包含 pch 是错误的。我只是想确认这种行为。pch是否能正常使用并且没有<SFML/Graphics.hpp>代码被重新编译?

Who*_*aig 4

如果标头的作者有任何盐,那么不会,它不会被重新编译。

PCH 包含完整的定义,包括#ifndef, #define, #endif包含保护逻辑。在 PCH 创建期间,文件将被拉入、编译,并正式定义包含保护标识符。在您的源代码中,所有#include "stdax.h"预编译内容都被包含在内。源代码包含用于编译的可疑标头。#ifndef但是,一旦找到定义的包含保护的 id,预处理器将跳过所有内容。注意:有可能可以为专门关闭PCH 的翻译单元重新编译它,但我怀疑您已经这样做了。

简而言之,你的做法是正确的,你的评估也是准确的。