Preprocessor
  • C Preprocessor is a text substitution tool, it instructs the compiler to do required pre-processing before the code is compiled
  • Replace Macro, include header files
  • #include
  • means copying the contents of another file in the current one
  • #include <filename>
  • #include "filename"
  • #include macroName
  • Define search path
  • #define STDIO <stdio.h>
    #include STDIO
    
    int main()
    {
    	printf("Hello World!\n");
    
    	return 0;
    }
    		
    #define
  • Replace identifier with replacement content before compiling program
  • #include <stdio.h>
    
    #define MESSAGE "Hello World!"
    #define PI 3.14
    
    int main()
    {
    	printf("%s\n", MESSAGE);
    	printf("%f\n", PI);
    
    	return 0;
    }
    		
  • Define function
  • #include <stdio.h>
    
    #define doubleNum(a) a*2
    
    int main()
    {
    	printf("%d\n", doubleNum(10));
    
    	return 0;
    }
    		
  • #, convert a parameter to a string
  • #include <stdio.h>
    
    #define OUTPUT(a) printf(#a)
    
    int main()
    {
    	OUTPUT(Hello\n);
    
    	return 0;
    }
    		
  • ##, joined a token with a string
  • #include <stdio.h>
    
    #define FUNCTION(name, a) int fun_##name() { return a;}
    
    FUNCTION(v1, 12);
    FUNCTION(v2, 2);
    
    int main()
    {
    	printf("%d\n", fun_v1());
    	printf("%d\n", fun_v2());
    
    	return 0;
    }
    		
    #ifdef, #ifndef, #elif, #else, #endif
    #include <stdio.h>
    
    int main()
    {
    
    #ifndef SYSTEM
    #define SYSTEM 1
    
    	if(SYSTEM == 1)
    		printf("Linux system ...\n");
    #endif
    
    #ifndef SYSTEM
    	printf("Windows system ...\n");
    #elif SYSTEM == 1
    	printf("Linux system ...\n");
    #else
    	printf("Mac system ...\n");
    #endif
    }
    		
    #error
  • causes preprocessing to stop at the location where the directive is encountered
  • //#define PI 3.14
    
    int main()
    {
    #ifndef PI
    #error NOT DEFINE PI
    #endif
    	return 0;
    }
    		
    #pragma
  • Issues special commands to the compiler
  • // main.c
    #include <stdio.h>
    
    int main(void)
    {
        #pragma omp parallel
        {
        printf("Hello, world.\n");
        }
    
      return 0;
    }
    		
    gcc -fopenmp main.c -o hello
    		
    Predefined Macro
    #include <stdio.h>
    
    int main() {
    
       printf("File :%s\n", __FILE__ ); // file name
       printf("Date :%s\n", __DATE__ ); // current date
       printf("Time :%s\n", __TIME__ ); // current time
       printf("Line :%d\n", __LINE__ ); // current line number
       printf("ANSI :%d\n", __STDC__ ); // 1, if the compiler complies with the ANSI standard
    
    }
    		
    Reference
  • Tutorialspoint
  • cnblogs