120 likes | 159 Views
Preprocessor. All preprocessor directives or commands begin with a #. E.g. #include <stdio.h> C program → Modified C program → Object Code Can appear anywhere in the program No “;” in the end. preprocessor. compiler. Preprocessor Directives. Macro definition #define, #undef
E N D
Preprocessor • All preprocessor directives or commands begin with a #. • E.g. #include <stdio.h> C program → Modified C program → Object Code • Can appear anywhere in the program • No “;” in the end preprocessor compiler
Preprocessor Directives • Macro definition • #define, #undef • File inclusion • #include • Conditional Compilation • #if, #ifdef, #ifndef, #elseif, #else • Others
#define • To define constants or any macro substitution. #define <macro> <replacement name> E.g. #define FALSE 0 #define TRUE !FALSE • To undefined a macro. E.g. #undef FALSE #define D 2 printf("%d",D); #undef D int D=6; printf("%d",D);
Define Functions • E.g. To get the maximum of two variables: #define max(A,B) A > B ? A:B • In the C code: x = max(q+r,s+t);
File inclusion • #include directive • Include the contents of another file at the point where the directive appears. • Why need file inclusion • Use built-in functions • E.g., printf(), rand(); • Reuse code double mean(int x,int y) { return (x+y)/2; } double mean(int ,int ); #include “test.h” printf("%f",mean(3,5)); test.cpp test.h Your code
File inclusion formats • #include <file> • Used for system header files • File contain function prototypes for library functions • <stdlib.h> , <math.h> , etc • #include "file" • Used for header files of your own program • looks for a file in the current directory first • then system directories if not found
Custom header files • Steps for creating custom header files • Create a file with function prototypes • Save as a .h file. E.g.: filename.h • Load in other files with • #include "filename.h" • Advantage • Reuse functions and data structure declaration
Conditional compilation • Useful when • machine-dependencies • setting certain options at compile-time. • Expressions • #if expression • #ifdef expression (same as #if defined ) • #ifudef • #elif and #else • #endif
Examples • Example: write programs that are portable to several machines or operating systems • #if defined(WINDOWS) • #elif defined(LINUX) • #elif defined(SOLARIS) • #endif • Example: Providing a default definition for a macro • #ifndef BUFFER_SIZE • #define BUFFER_SIZE 256 • #endif
Inline functions Ret_Type inline func_name(params); e.g. int inline func(void); • Inline hints to the compiler that this function should be unrolled an inlined into wherever it is called. This can avoid function call overhead. • Problems with inline: • The compiler may happily ignore this. It’s kind of like the register keyword in this manner. It is merely a hint; it is not a command. • You may (and probably will) make your program size larger. • Read the previous bullet as “cache miss” or “page fault”.