Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with include guard

When I add an include guard to my header file for a Visual C++ project, it gives me the following warning and error:

warning C4603: '_MAPTEST_H' : macro is not defined or definition is different after precompiled header use

Add macro to precompiled header instead of defining here

.\MapTest.cpp(6) : use of precompiled header** // the precompiled header stdafx.h is included in this line

.\MapTest.cpp(186) : fatal error C1020: unexpected #endif

but when I add the precompiled header before the include guard, no warning or error is emitted. What is the reason for this?

like image 940
Izza Avatar asked May 31 '10 06:05

Izza


People also ask

Why are include guards important?

Include guards ensures that compiler will process this file only once, no matter how many times it is included. Include guards are just series of preprocessor directives that guarantees file will only be included once. Preprocessors used: #ifndef: if not defined, determines if provided macros does not exists.

Does C++ need header guards?

Without a header guard, a code file could end up with multiple (identical) copies of a given type definition, which the compiler will flag as an error.

What is the purpose of header guards in C++?

Header guards are designed to ensure that the contents of a given header file are not copied, more than once, into any single file to prevent duplicate definitions. This is a good thing because we often need to reference the contents of a given header from different project files.


2 Answers

Two problems I can think of:

  1. According to this, Visual C++ won't compile anything before the line where you include stdafx.h - so that line needs to be the very first one in the file. If you put it after the macro definition, it gets skipped, hence the errors you're seeing.

  2. Identifiers starting with a leading underscore and a capital letter (or double leading underscores) are reserved, which might be causing a name conflict. see this answer for more details.

like image 149
tzaman Avatar answered Sep 29 '22 19:09

tzaman


Try opening stdafx.cpp and add your macro definition there! I hope your problem is solved

like image 44
Sparsh Jain Avatar answered Sep 29 '22 18:09

Sparsh Jain