Question

I have a very basic project in VS2012 using precompiled headers. I know that I'm supposed to add all "common" includes to stdafx.h and that I need to include this in each .cpp file. Thus, the basic setup looks like this:

Foo.h:

#ifndef FOO_H
#define FOO_H

class Foo {

public:
    Foo();
    ~Foo();

    void do(string str);
};
#endif

Foo.c:

#include "stdafx.h"
#include "Foo.h"

void Foo::do(string str) {}

in stdafx.h:

#include <string>
using namespace std;

Without precompiled headers, I'd put #include <string> into foo.h, since it has to know about the declaration of string. But how this foo.h know about string in this setup? (Note that stdafx.h is only included in the .cpp files).

Note: I have a working example that uses precompiled headers; the question is about how this works.

Était-ce utile?

La solution

This is because the compiler processes headers in the order in which they appear in the main compilation unit.

Because the .cpp file included <string> (indirectly via "stdafx.h"), the contents of <string> are known to the compiler, and can be used by code that follows, even code pulled in from header files.

It is fragile though, because including your header file without first including <string> will cause errors.

Autres conseils

You can look on the pre-compiled headers as a kind of cache for header files. The compiler analyzes a set of headers when it first encounters it (usually when compiling stdafx.cpp), compiles them, and then has the results ready for any module that needs them.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top