Tuesday 24 December 2013

Sharing User Defined C Header Files in Linux


  In C/C++ header files are used to store common code so that they can be reused at a later stage. Header files are having an extension .h in C/C++. In this post I am discussing the different ways to share a user defined C header file in Linux.

1.  The first technique is to store the header file in the current directory along with the C program accessing the header file. In this case the header file name is included by using Double Quotes instead of angle brackets.

For example the name of the header file be myheader.h. This header file can be included in a C program as shown below,

#include "myheader.h"

2. Another technique is to store the header file in a separate directory and add the whole path while including the header file. Here also the include statement uses Double Quotes instead of angle brackets. 

For example the header file myheader.h is stored in the directory /home/myheaders. Then this header file can be included in a C program as shown below,

#include "/home/myheaders/myheader.h"

3. Finally if you are satisfied with the quality of your header file you can add it to the standard header directories in Linux. The two standard header directories in Linux are,
  • /user/local/include - This directory is used to store header files for third-party libraries.
  • /usr/include - This directory is used to store Operating System Header files.  
For example if the header file myheader.h is copied into one of the two standard header directories mentioned above, then the header file can be included in a C program as shown below,

#include <myheader.h>      

Here Angle Brackets are used in the include statement instead of double quotes. Hence the compiler searches for the header file only in the standard header libraries. 

No comments:

Post a Comment