宏定义

五种宏定义

  1. 源代码

    	//------------------
    
    	#define ONE_AND_ONE_REPLACEMENT test[] = {123,123}
    
    	//-------------
    
    	#define FUNCTION_REPLACE(param)  int param = 12
    
    	//--------------
    
    	#define FUNCTION_REPLACE_FUNC(x,y) (x)>(y)?(x):(y)
    
    	//----------------
    
    	#define NUM 10
    
    	#define ANY2STR(x) #x
    	#define FUNCTION_REPLACE_TO_STR(test) ANY2STR(test)
    
    	//------------
    
    	#define FUNCTION_MANY_ARGS(...) { __VA_ARGS__ }
    
    	//------------
    
    	#define DEFINE_FUNCTIONS(key) int get##key(){return 0;}
    	void set##key(int n){int t = n;}
    
    
    	DEFINE_FUNCTIONS(hello)
    	DEFINE_FUNCTIONS(world)
    	DEFINE_FUNCTIONS(this)
    	DEFINE_FUNCTIONS(is)
    
    	#undef DEFINE_FUNCTIONS
    
    	//-------------------
    
    	#define DEFINE_TWO(pre,next) void pre##  ##next(){}
    
    	DEFINE_TWO(hello,world)
    	DEFINE_TWO(frando,thethy)
    
    	#undef DEFINE_TWO
    
    	int main()
    	{
    	int ONE_AND_ONE_REPLACEMENT;
    	FUNCTION_REPLACE(hello);
    	char str[] = FUNCTION_REPLACE_TO_STR(NUM);
    	int jiejie[] = FUNCTION_MANY_ARGS(1,2,3,4,5,6);
    	}
    
  2. 预编译后的代码

    	# 1 "test.cpp"
    	# 1 "<built-in>"
    	# 1 "<命令行>"
    	# 1 "/usr/include/stdc-predef.h" 1 3 4
    	# 1 "<命令行>" 2
    	# 1 "test.cpp"
    	# 30 "test.cpp"
    	int gethello(){return 0;}void sethello(int n){int t = n;}
    	int getworld(){return 0;}void setworld(int n){int t = n;}
    	int getthis(){return 0;}void setthis(int n){int t = n;}
    	int getis(){return 0;}void setis(int n){int t = n;}
    
    
    
    
    
    
    
    	void helloworld(){}
    	void frandothethy(){}
    
    
    
    	int main()
    	{
    	   int test[] = {123,123};
    	   int hello = 12;
    	   char str[] = "10";
    	   int jiejie[] = { 1,2,3,4,5,6 };
    	}
    

  1. 纯粹的一比一替换

    	#define ONE_AND_ONE_REPLACEMENT test[] = {123,123}
    
  2. 参数类型的宏

    	#define ONE_AND_ONE_REPLACEMENT test[] = {123,123}
    
  3. 多参数类型的宏

    	#define FUNCTION_REPLACE_FUNC(x,y) (x)>(y)?(x):(y)
    
  4. 变参数类型的宏

    	#define FUNCTION_MANY_ARGS(...) { __VA_ARGS__ }
    
  5. 宏生成字符串

    	#define NUM 10
    
    	#define ANY2STR(x) #x
    
    	#define FUNCTION_REPLACE_TO_STR(test) ANY2STR(test)
    
  6. 拼接类型的宏

    • 宏定义方法
      	#define DEFINE_FUNCTIONS(key) int get##key(){return 0;}
      
      	void set##key(int n){int t = n;}
      
      	DEFINE_FUNCTIONS(hello)
      
      	DEFINE_FUNCTIONS(world)
      
      	DEFINE_FUNCTIONS(this)
      
      	DEFINE_FUNCTIONS(is)
      
      	#undef DEFINE_FUNCTIONS
      
    • 多参数去空格无缝拼接
      	#define DEFINE_FUNCTIONS(key) int get##key(){return 0;}
      	void set##key(int n){int t = n;}
      
      
      	DEFINE_FUNCTIONS(hello)
      	DEFINE_FUNCTIONS(world)
      	DEFINE_FUNCTIONS(this)
      	DEFINE_FUNCTIONS(is)
      
      	#undef DEFINE_FUNCTIONS