Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C and C++, why is each .h file usually surrounded with #ifndef #define #endif directives?

Why does each .h file starts with #ifndef #define #endif? We can certainly compile the program without those directives.

like image 909
user133466 Avatar asked Jan 10 '10 21:01

user133466


People also ask

What is a .h file in C?

A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.

What two things are most commonly listed in the .h file of a class?

Things like class declarations, function prototypes, and enumerations typically go in header files.

What typically goes into a .h file?

A file saved with h file extension is a header file used in C/C++ files to include the declaration of variables, constants, and functions. These are referred by the C++ implementation files that contain the actual implementation of these functions.

What is the purpose of this line in a header file?

The primary purpose of a header file is to propagate declarations to code files. Header files allow us to put declarations in one location and then import them wherever we need them.


2 Answers

It's a so-called "include guard". The purpose is to prevent the file from having to be parsed multiple times if it is included multiple times.

like image 69
janneb Avatar answered Sep 24 '22 02:09

janneb


It prevents multiple inclusions of a single file. The same can be done using

#pragma once

directive, but those #ifndefs are standard thus supported by every compiler.

like image 31
el.pescado - нет войне Avatar answered Sep 20 '22 02:09

el.pescado - нет войне