5

I have searched for a while on this, but I keep getting answers that do not answer this specific scenario.

I have a class called VisibleGameObject. I am wondering what happens if I put my normal includes in the header (so that other developers can use the same class), and put the same include in my pre compiled header stdafx.h I don't want developers dependent on my 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;
};

Implementaion:

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

...

PCH:

// 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>

When I build my project (after I have compiled once), does #include <SFML/Graphics.hpp> get recompiled every time? Because it is included in the header file of this class. I think what happens is that the pch is included first in the cpp file's translation unit and then #include <SFML/Graphics.hpp> is include guarded so the pch works normally and my include is ignored. In Visual Studio, it is an error to not include the pch first. I just want to confirm this behaviour. Does the pch get used normally and no <SFML/Graphics.hpp> code is recompiled?

Mr_Moneybags
  • 3,927
  • 3
  • 19
  • 15

1 Answers1

4

If the author of the header has any salt at all, then no, it won't be recompiled.

The PCH includes the full definition, including the #ifndef, #define, #endif include guard logic. During PCH-creation the file will be pulled in, compiled, and the include guard identifier formally defined. In your source that follows any #include "stdax.h" all that precompiled content is slurped in. The source will include the suspect header for compilation. However, the preprocessor will skip all the content once the include guard's #ifndef id is found as defined. Note: It is possible it can be recompiled for a translation unit that specifically has PCH turned off, but I doubt you've done that.

In short, you're doing it correctly, and your assessment is accurate.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141