Fwd: Re: [courses] [C] lesson7/8 - Various things

Laura Bowser lbowser at andrew.cmu.edu
Wed Nov 13 11:21:42 EST 2002


One of the best examples for using the conditional preprocessor directives is
when debugging with print statements.

example code:
****************************************************

#define ENDLOOP 30

int main(int argc, char **argv) {

	int i, j;

	for (i =0; i < ENDLOOP; i ++)
		for (j = 0; j < ENDLOOP; j++) {
#ifdef DEBUG
		printf("i: %d, j: %d\n", i,j);
#endif /* DEBUG */
		/* do whatever with these values */
		}
	return 0;
}


*********************************************************
When you compile this, you can do what you'd normally do:
gcc -o example example.c

OR
you can define DEBUG and have all the debug statements printed out
gcc -o example -DDEBUG example.c

(if you've ever compiled your kernel, you'll see a lot of these -D statements
go by)

now, you can turn debugging off and on "on-the-fly" without having to go
through and comment out all your print statments, which may or may not
actually be debugging statements.

Another common example of using the conditionals is when creating your own
header files.  Sometimes every C file in your project/code will include the
same header file, and since you can never guarantee the order in which things
are included, you want to keep these files from being included twice.

example header file
*********************************************************************
#ifndef _MYHEADER_H_   /* if _MYHEADER_H_ isn't defined...... */
#define _MYHEADER_H_  /.* define it */

/* all your declarations */

#endif  /* _MYHEADER_H_ */

**********************************************************************

now, no matter how many times you inlcude it in your c files, it will only
actually be included once!


Laura

> The #ifdef, #endif, #ifndef, and #else are used in conditional
> compilation.  I've seen this occur in source code that is written
> for multiple platforms, like DOS and UNIX.  The best way to understand
> this stuff is to look at a working example. Unfortunately, the chapter
> in the book was sorely lacking in working examples, and I can't come
> up with one off the top of my head.  Maybe someone on the list can write
> an example that illustrates conditional compilation using the above
> preprocessor directives?  If I find one in my books, I'll post it.


-- 
Public key available at 
http://www.elwing.org/~elwing/lbowser.gpg



More information about the Courses mailing list