In this paper, we mainly record the pre-C + + preprocessor directives, and the common preprocessing directives are:
#空指令, without any effect
#include包含一个源代码文件
#define定义宏
#undef取消已定义的宏
#if如果给定条件为真, the following code is compiled
#ifdef如果宏已经定义, the following code is compiled
#ifndef如果宏没有定义, the following code is compiled
#elif如果前面的 # If the given condition is not true and the current condition is true, compile the following code
#endif结束一个 # If ... #else条件编译块
#error停止编译并显示错误信息
The most common form of conditional compilation commands is:
#ifdef identifiers
Procedure Section 1
#else
Procedure Section 2
#endif
Cases:
BOOL #define ture 1#define false 0#endif
In the early VC, the bool variable is represented by 1,0, which can be defined so as to ensure program compatibility
It is important to use #ifdef and #ifndef in header files to prevent double-defined errors.
// main.cpp File "cput.h" "put.h" int main () { cput (); Put (); " Hello world! " << Endl; return 0 ;}
// cput.h header file #include <iostream>using namespace STD; int Cput () {cout << " hello world! " << Endl; return 0 ;}
// put.h Header File "cput.h"int put () { cput (); return 0 ;}
Compilation error, two times in Main.cpp contains Cput.h
Attempt to simulate the restoration of the compilation process;
When the compiler compiles main.cpp
//pre-compilation loads the header file into the main.cpp file first//Expand # include "cput.h" content#include <iostream>using namespacestd;intCput () {cout<<"Hello world!"<<Endl; return 0;}//Expand # include "put.h" content//Put.h contains the cput.h first unfold#include <iostream>using namespacestd;intCput () {cout<<"Hello world!"<<Endl; return 0;}intput () {cput (); return 0;}intMain () {cput (); Put (); cout<<"Hello world!"<<Endl; return 0;}
It is obvious that after merging the expanded code, two times the Cput () function is defined;
If you change the cput.h to the following form:
#ifndef _cput_h_ #define _cput_h_<iostream>usingnamespace std; int Cput () { "Hello world! " << Endl; return 0 ;} #endif
When the compiler compiles main.cpp, the merged main.cpp file will be like this:
#ifndef _cput_h_#define_cput_h_#include<iostream>using namespacestd;intCput () {cout<<"Hello world!"<<Endl; return 0;}#endif#ifndef _cput_h_#define_cput_h_#include<iostream>using namespacestd;intCput () {cout<<"Hello world!"<<Endl; return 0;}#endifintput () {cput (); return 0;}intMain () {cput (); Put (); cout<<"Hello world!"<<Endl; return 0;}
This compilation succeeds by running, because the cput.h contained in the expanded put.h does not take effect, and the macro is defined earlier _cput_h_
C + + preprocessing directive # define, conditional compilation #ifdefine