Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a guard block for a header file in C++?

I'm trying to make a C++ class using the Code::Blocks IDE and there is a field called "Guard block." I've done a search and haven't been able to find any useful information. What is this field for? Thanks.

like image 498
chrislgarry Avatar asked Oct 20 '11 20:10

chrislgarry


2 Answers

Guard blocks are used to protect against the inclusion of a header file multiple times by the same compilation unit (c++ file). They look something like this:

// Foo.h
#ifndef INCLUDE_FILE_NAME_HERE_H_
#define INCLUDE_FILE_NAME_HERE_H_

class Foo
{
};


#endif

If you include the same file multiple files, you will end up with multiple definition error. Using of include guards isn't necessary in small projects but becomes critical in any medium to large sized projects. I use it routinely on any header files I write.

like image 136
Lou Avatar answered Sep 29 '22 00:09

Lou


Guard blocks are used to prevent a header file being included multiple times in a single translation unit. This is often a problem when you include a number of header files that in turn include common standard header files.

The problem with multiple inclusions of the same file is that it results in the same symbol being defined multiple times.

Guard clauses can be handled with #define and #ifdef statements but are much simpler with the non-standard, but universal, #pragma once.

// foo.h
#pragma once

int foo(void);
// etc.
like image 24
David Heffernan Avatar answered Sep 29 '22 01:09

David Heffernan