15

更新:

在我的头文件中包含 stdafx.h 有什么影响?


我在 Linux/Eclipse CDT 中开始了一个 C++ 项目,并将其导入 Visual C++/Windows。

在 Visual C++ 中,我开始使用预编译头文件来加速编译并定义 stdafx.cpp 和 stdafx.h。

这是我的 stdafx.h

#pragma once

#include <string>
#include <vector>
#include <map>
...

和我的 stdafx.cpp

#include "stdafx.h"

在每个 .h 和 .cpp 文件中,我都有以下内容:

#pragma once //if in a header file
#include "stdafx.h"

对于发布和调试,我都有“创建预编译头文件 (/Yc)”。它在调试模式下编译得很好,但在发布模式下它会不断报告

error LNK2005: ___@@_PchSym_@00@UfhvihUaszlaDUwlxfnvmghUnnlUhixUnnlPeDUnnlPeDUivovzhvUvmgrgbOlyq@ already defined in A.obj

如果我同时切换到“使用预编译头”,我会同时进入调试和发布

fatal error C1854: cannot overwrite information formed during creation of the precompiled header in object file:

有谁知道发生了什么?

4

4 回答 4

30

您仅为 stdafx.cpp 放置“创建预编译头文件”。然后对所有其他“.cpp”文件“使用预编译头文件”。最后,include "stdafx.h"在每个“.cpp”文件的开头(通常不在头文件中。

于 2009-09-09T02:01:19.760 回答
6

编译器/Yc选项用于为编译操作创建预编译头文件。该/Yu选项指示编译器使用预编译的头文件。

您将始终/Yu在项目设置中使用该选项。在文件的属性页中,将设置stdafx.cpp该选项。/Yc

.cpp重要的是要了解每个文件都有单独的编译选项。

有关 /Y 选项的详细信息,请参见此处

于 2009-09-09T02:05:59.037 回答
4

你把我认为导致编译器忽略指令的#pragma once前面放了。#include "stdafx.h"#pragma once

另外,我认为您根本不应该将该#include "stdafx.h"行放入头文件中。

于 2009-09-09T01:54:10.500 回答
1

使用“stdafx.h”的结果不受 PreCompiled Header 系统的影响。如果关闭 Create PCH/Use PCH,代码将编译并创建相同的输出,但速度较慢。这也是您可以在可移植代码中使用它的原因(不像#pragma once

于 2009-09-09T14:34:54.030 回答