C++ Header Guard Syntax and Header Placement

My question is on proper syntax and usage of header guards. For example if I am including a few common libraries in my C++ code can I make a header guard like what is shown below? Also, from the documentation I could find on header files it was suggested to put your header guard in a header file. I am using Microsoft Visual Studio. Can I just place my header guard and #include files in my main source file? Or is this a bad practice? I know you can use #pragma to function as a header guard. However, this is not a supported standard so I am trying to avoid using it.

#ifndef HEADER_GUARD
#define HEADER_GUARD
#include <iostream> 
#include <fstream>  
#include <string>
#include <iomanip>
#endif

Any help would be greatly appreciated!

Upvotes: 0

Views: 782

Answers (1)

Build Succeeded
Build Succeeded

Reputation: 1150

You should not write the header guard in source code (.cpp) file.

We should avoid the double header guard as well The use of double include guards in C++

Header guard is to avoid multiple time inclusion of header file during compilation of code.

Also, while adding the #include file, keep in mind that we should not add the unwanted files there. e.g. Consider case if source file requires to #include <iostream> but you included in header file then this should be avoided. Such case #include <iostream> in source file only.

#pragma once is supported by many compilers but it's not language standard and it do not guarantee when file are referenced from remote location and different disks.

Upvotes: 1

Related Questions