Thursday 15 December 2011

How to reduce compile time dependencies


How to reduce compile time dependencies

The main culprit behind compile time dependencies is the huge amount of header files that are included by the compiler. Header files that are required in the code will obviously be added, but some programmers out of just habit include some useless header files as well. For eg :
In this code few header file will not be reqired

//Header files:
#include<iostream>
#include<ostream>
#nclude<B.h>
#nclude<C.h>
#nclude<A.h>


claas A {


B *obj;
C *obj;
 virtual std::ostream& print( std::ostream& ) const;


}

From the above code we can remove B.h and C.h straight away and use forward declaration instead of includeing those header files. Now what the hell is this FORWARD DECLARATION...??
Forward declaration is when we just declare and dont define.
Suppose we are just using references or pointers to B or C, then we can get away with forward declaration and dont need to include the header files.

  class B ; //Forward declaration only no need to include
  
  class A {
    private:
      B* fPtrB ;
    public:
      void mymethod(const& B) const ;
  } ;
But if we derive from B or C or uses objects of B or C, then we need to include their header files.

#include<B.h> //Header file included
  class A : public B{
  
  } ;
  
  class C {
    private:
      B objB ;
    public:
      void mymethod(B par) ;   
  }

Also we can remove #include<iostream> as well, dont be confused with the word stream, its not necessary that whenever you encounter the word stream you include <iostream>.
Here ostream is used and when can use #include<ostream> only and it will suffice.


So after clearing all the unwanted header files, heres what our code looks like :

//Header files:


#include<ostream>
#nclude<A.h>


claas A {


B *obj;
C *obj;
 virtual std::ostream& print( std::ostream& ) const;


}

One more thing we can do here is that we can use <iosfwd> instead of <ostream>,
what it will do is forward declare all the necessary things for ostream.

Some of you might also be wondering that whats the difference between function prototype and forward declaration.

In writing a function prototype you don't need to define parameter names, just their data type will suffice
int add( int, int );
but in forward declaration you need to specify their name as well,tough both will fulfill you requirements.

1 more thing that might interest you guys is that, think what will happen when you only declare the function and don't define it and then call it.........???

int add(int a, int b)

int main()
{
cout<<"Sum of 5 and 10 is "<<add(5,10);

return 0;
}

We have declared add but never defined it and also used it in our code...
So compiling will succeed but linking will fail and it will give error unresolved external symbol.

No comments:

Post a Comment