0

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!

  • 1
    Don't put header guards anywhere but headers. And honestly, short of a precompiled header set, headers of headers isn't very helpful either. As an engineer you want to see the header list *in your source file* and know what is being pulled in; not see a list of things you need to open individually, checking to see what *they* pull in. And believe me, that gets to be a real PITA three or four levels deep. – WhozCraig Jan 13 '20 at 22:51

1 Answers1

1

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.

Build Succeeded
  • 1,153
  • 1
  • 10
  • 24