What Are #ifndef And #define Used For In C++?

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeWhat are #ifndef and #define used for in C++?

#ifndef and #define are known as header guards. Their primary purpose is to prevent C++ header files from being included multiple times.

svg viewer

Example​

Consider a sample header file which uses these guards:

#ifndef HEADERFILE_H #define HEADERFILE_H // some declarations in // the header file. #endif

Explanation

When the code is compiled, the preprocessor checks whether HEADERFILE_H has been previously defined. If this is the first time we have included the header, HEADERFILE_H will not have been defined. Consequently, the compiler defines HEADERFILE_H and includes the contents of the file.

If the header is included again into the same file, HEADERFILE_H will already have been defined from the first time that the contents of the header were included; the ifndef guard will then ensure that the contents of the header will be ignored.

These header guards prevent redeclaration of any identifiers such as types, enums, classes, and static variables. They also prevent recursive inclusions; for example, a case where “file1.h” includes “file2.h” and “file2.h” includes “file1.h”.

Relevant Answers

Explore Courses

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved

Tag » Arduino Ifndef Example