Monday, April 1, 2013

Coding Practices: Which is better? #pragma once or #include Guard

In C or C++, we need to ensure that a header file is not included more than once.
Let us say you have a header file named add.h which declares an adding function (We are not discussing the corresponding cpp files for simplicity). Now let us say you have another header file my_math.h which declares further mathematical functions. If you want to use previously mentioned adding function here, you need to include add.h in my_math.h file.When you want to use functions from both header files in, say, main.cpp, you should ensure that you are including only my_math.h. Otherwise you will get multiple declaration error for adding function because it is coming from both add.h and my_math.h as shown below.

add.h: add(int a, int b)
            /   \
          /       \
        /           \
my_math.h    /
      /           / 
    /           /             
     main.cpp   

As the example case is very simple it is easy to avoid the inclusion of add.h in main.cpp. But doing that will be difficult and sometimes impossible in real life programs. The standard solution for this is to use #include guard as shown below

/*add.h*/
#ifndef _ADD_H_
#define _ADD_H_

/*
Your content goes  here
*/ 

#endif    /*   _ADD_H_  */                                      

 The per-processor will ensure that only one copy of the add.h content is passed to compiler.

A new and easy alternate is adding

#pragma once

at the beginning of the code. This looks very neat. But it is not yet standard. So for better portability we should use #include guard.


References:
  1. http://en.wikipedia.org 
  2. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
  3. http://www.codeproject.com/Articles/26222/C-Coding-Practices-Guide
  4. http://www.possibility.com/Cpp/CppCodingStandard.html
  5. http://stackoverflow.com/questions/1143936/pragma-once-vs-include-guards 

No comments:

Post a Comment