VS2012预编译头:我的.h文件如何知道包含在stdafx.h

VS2012 precompiled headers: how does my .h file know about includes in stdafx.h?

本文关键字:何知道 包含 stdafx 文件 VS2012 编译 我的      更新时间:2023-10-16

我有一个非常基本的项目在VS2012使用预编译头。我知道我应该将所有"公共"包含添加到stdafx.h中,并且我需要将其包含在每个.cpp文件中。因此,基本设置如下所示:

foo:

#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) {}
在stdafx.h:

#include <string>
using namespace std;

如果没有预编译的头文件,我将#include <string>放入foo.h中,因为它必须知道string的声明。但我是怎么知道string的呢?(注意stdafx.h只包含在.cpp文件中)。

注意:我有一个使用预编译头文件的工作示例;问题是这是如何工作的

这是因为编译器按照头文件在主编译单元中出现的顺序处理头文件。

因为.cpp文件包含<string>(间接通过"stdafx.h"), <string>的内容可以被编译器知道,并且可以被后面的代码使用,甚至可以从头文件中提取代码。

这是脆弱的,因为包括你的头文件没有首先包含<string>将导致错误。

您可以将预编译的头文件看作是头文件的一种缓存。编译器在第一次遇到一组头文件时(通常是在编译stdafx.cpp时)对其进行分析,编译它们,然后为任何需要它们的模块准备好结果。