I want some examples of C preprocessor directives, such as:
#define pi 3.14
#define MAX 100
I know only this. I want to know more than this, more about preprocessor directives.
I want some examples of C preprocessor directives, such as:
#define pi 3.14
#define MAX 100
I know only this. I want to know more than this, more about preprocessor directives.
The biggest example would be
#include<stdio.h>
But there are a fair amount. You can also define macros:
#define MAX(X,Y) (((X) > (Y)) ? (X) : (Y))
And use header guards
#ifndef A_H
#define A_H
// code
#endif
There are proprietary extensions that compilers define to let you give processing directives:
#ifdef WIN32 // WIN32 is defined by all Windows 32 compilers, but not by others.
#include <windows.h>
#else
#include <unistd.h>
#endif
And the if statement cause also be used for commenting:
#if 0
int notrealcode = 0;
#endif
I often use the preprocessor to make debug builds:
#ifdef EBUG
printf("Debug Info");
#endif
$ gcc -DEBUG file.c //debug build
$ gcc file.c //normal build
And as everyone else has pointed out there are a lot of places to get more information:
Are you entirely familiar with the fundamentals, e.g. as covered on wikipedia? Or do you need an elementary tutorial? or what?
There's a lot more to the processor than #define. Don't forget #include and conditional compilation.
This will stop the compile if the conditional fails.
#define WIDTH 10
#define HEIGHT 20
#if WIDTH < HEIGHT
# error "WIDTH must be greater than or equal to HEIGHT"
#endif
C Preprocessor Man pages http://gcc.gnu.org/onlinedocs/cpp/index.html
The most important one:
#ifndef THIS_HEADER_H
#define THIS_HEADER_H
// Declarations go here
#endif //THIS_HEADER_H
This keeps a header file from being included in a single C file multiple times.
For gcc sources I like to use __LINE__
, as in:
printf("%s: %d: Some debug info\n", __func__, __LINE__);
For debugging purposes.