Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1487907
  • 博文数量: 226
  • 博客积分: 3997
  • 博客等级: 少校
  • 技术积分: 2369
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-19 17:26
个人简介

Never save something for a special occasion. Every day in your life is a special occasion.

文章分类

全部博文(226)

文章存档

2018年(5)

2017年(11)

2016年(1)

2015年(17)

2014年(14)

2013年(30)

2012年(5)

2011年(52)

2010年(107)

分类: C/C++

2010-07-30 20:57:32

 
宏定义示例
 
1 条件包含
#ifndef MAIN_H_
#define MAIN_H_
// 此头文件内容
#endif
此条件编译的作用是:阻止头文件被多次include,多次include就会出现重复的定义情况。

2 条件编译
例:
// #define _DEBUG
#include
int main()
{
#ifdef _DEBUG
 printf("debug information...\n");
#else
 printf("no debug information...\n");
#endif
return 0;
}
第一次使用 gcc -D_DEBUG main.c
第二次使用 gcc main.c
运行两次的结果看
 
3 定义标志符
例:
#include
#define PI 3.1415
#define LANGUAGE_EN 1
main(){
#if LANGUAGE_EN
 printf("Value of PI is %f\n", PI);
#else
 printf("PI 的值是 %f\n", PI);
#endif
return 0;
}
 
例:
// 带参数"宏函数"
#define SQ_ERR(x) (x*x)
#define SQ_OK(x) ((x)*(x))
int main(){
int i = 1;
printf ("SQ_ERR(3) value is %d\n",SQ_ERR(3));
printf ("SQ_ERR(1+2) value is %d\n",SQ_ERR(1+2));
printf ("SQ_OK(3) value is %d\n",SQ_OK(3));
printf ("SQ_OK(1+2) value is %d\n",SQ_OK(1+2));
printf ("i=1, SQ_OK(i++) value is %d\n",SQ_OK(i++));  // 有副作用的用法!
return 0;
}
 
例:
// 可变参数宏 // VC6.0 编译不通过
#define PRINT(...) printf(__VA_ARGS__)
#include
int main(){
PRINT("%s %s","你好,","\n");
return 0;
}
 
例:
#define alarm printf
void main()
{
    alarm("编译警告:未包含printf所在头文件 stdio.h");
}

4、##和#的用法
## 是连接符号 连接两个宏
#  是把名字代替成字符串
 
例:
//#include
#define VC_Say(a) VC_##a
void VC_printf(const char* p )
{
 printf("提示:%s\n",p);
}
void VC_alarm(const char* p )
{
 printf("警告:%s\n",p);
}
int main()
{
 VC_Say(printf)("编译通过!");
 VC_Say(alarm)("没有包含printf所在头文件!");
 return 0;
}
 
例:
#include
#define TO_STR(p) #p
int main(){
// puts( TO_STR(这些内容不需要加引号,#会将它转换为串) );
puts(#奇怪,这一行去不能通过编译);
return 0;
}
 
 
 
欢迎随时补充!
 
阅读(929) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~