Visual C++ Precompiled Headers errors

邮差的信 提交于 2020-01-12 04:30:40

问题


Update:

What are the effects of including stdafx.h in my header files?


I started on a C++ project in Linux/Eclipse CDT and imported it into Visual C++/Windows.

In Visual C++, I started using precompiled headers to speed up compilation and defined stdafx.cpp and stdafx.h.

Here's my stdafx.h

#pragma once

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

and my stdafx.cpp

#include "stdafx.h"

In every .h and .cpp file, I have the following:

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

For both release and debug, I have "Create Precompiled Header (/Yc)". It compiled fine in debug mode, but in release mode it keeps reporting

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

If I switch both to "Use precompiled header", I get in both Debug and Release

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

Does anyone know what's going on?


回答1:


You put "create precompiled header" only for stdafx.cpp. Then "use precompiled header" for all of the other ".cpp" files. Finally, have include "stdafx.h" at the start of each ".cpp" file (not usually in the header files.




回答2:


The /Yc compiler option is used to create a pre-compiled header for a compilation action. The /Yu option instructs the compiler to use a pre-compiled header.

You will always use the /Yu option in project settings. In the property pages for your stdafx.cpp file, the /Yc option will be set.

It is important to understand that there are separate compilation options for each .cpp file .

See here for details of the /Y options.




回答3:


You put the #pragma once before the #include "stdafx.h" which I think is causing the compiler to ignore the #pragma once directive.

Also, I don't think you should be putting the #include "stdafx.h" line into the header files at all.




回答4:


The results of using "stdafx.h" are not influenced by the PreCompiled Header system. If you turn off Create PCH/Use PCH, the code compiles and creates the same output, except it does so slower. This is also why you can use it in portable code (unlike #pragma once)



来源:https://stackoverflow.com/questions/1397190/visual-c-precompiled-headers-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!