One defining purpose

One of the biggest impediments to learning C is having to learn the different between things that are there because they are necessary, and things that are there because of good practice. I kept encountering tokens being defined in header files that were never reference or used again. For example, if I create a header file called myheader.h in an IDE (or if I see this sort of thing in other people’s code) I would see…

#ifndef _MYHEADER_H

#define _MYHEADER_H


…but you’d often never see this token used anywhere else. Most people learning will remove it to see what happens and find that there is no consequence. I just accepted it as one of those things and moved on.

While researching serial communication and the termios structure I decided to track down where termios and the field values were defined. If you go to /usr/include/ and open termios.h you find that it’s just a front to define a few things and to point to the “real” termios.h that has all the meat (for me located in /usr/include/i386-linux-gnu/bits/). In the “real” termios.h you find that it checks whether or not _TERMIOS_H, defined in the other termios.h, has been defined. If it hasn’t it gives an error that you need to include the termios.h in /usr/include, not the one in /bits/. So, “correct header file inclusion” is one purpose for defining these tokens, it seems. Good to know.


This entry was posted in Hobbies, Programming. Bookmark the permalink.

One Response to One defining purpose

  1. Anonymous says:

    You typically see this as a strategy to prevent duplicate declaration problems. It has the effect of only allowing the pre-processor to process the .h file once – even if it is included from multiple modules.

    A typical example is typedef’ing a struct in a .h file then including the .h file in two separate .c modules that are compiled and linked together. Without the ifndef/define/endif sequence, the .h file would be processed twice (once for each include reference) and you would get a compiler error that the typedef has a duplicate definition.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s