linux c预处理器

原文地址http://daileinote.com/computer/c_base/10

#define

定义明显常量(符号常量),  定义宏命令,定义后,编译器在预处理阶段就会直接替换值,所以一些关系到运算符优先级的尽量多的使用括号。

#include<stdio.h>

#define PI 3.14

//字符串化
#define say_2(x) printf("the square of " #x " is %d\n", (x*x))

//使用参数
#define square(x) x*x

//预处理器粘合剂:##运算符
#define ARG(n) int arg_ ## n

void main()
{
    printf("%d %f\n", square(2), PI);
    say_2(2);
    
    ARG(1) = 3;     //int arg_1 = 3;
    ARG(2) = 4;     //int arg_2 = 4;
    
    //3    4
    printf("%d %d\n", arg_1, arg_2);
}

 

#include

当预处理器发现这个的时候会去搜索路径上搜索该文件并把里面的内容替换进来。

#include <stdio.h>    //在标准路径中搜索
#include "tmp.h"      //先在当前路径搜索,搜索不到才会到标准路径
#include "/lib/tmp.h" //去绝对路径搜索

 

其他指令如#if#ifdef#ifndef#else#elif#endif以及预定义宏

#include<stdio.h>

#define PI 3.14

//取消定义
#undef PI

//如果定义了MO,也就是之前有过#define MO xxx
#ifdef MO
    #include "tmp.h"
    #define NAME "沧浪水"
#else
    #include "a.h"
    #define URL "http://www.freecls.com"
#endif

//如果未定义
#ifndef VERSION
    #define VERSION 2.1
#endif

//#if后面跟整形常数表达式
#define SYS 1

#if SYS == 1
    #include "a.h"
#elif SYS == 2
    #include "a.h"
#else
    #include "a.h"
#endif

void main()
{
    printf("the file is %s\n", __FILE__);
    printf("the date is %s\n", __DATE__);
    printf("the time is %s\n", __TIME__);
    //printf("the version is %d\n", __STDC_VERSION__);  //c99以上才支持
    printf("the line is %d\n", __LINE__);
    printf("the function is %s\n", __func__);
}

 

#line是用来重置__LINE__和__FILE__的宏报告的行号和文件名、#error是用来报错的

#include<stdio.h>

#line 10 "aa.c"

#ifndef __STDC_VERSION__
#error not above c99
#endif

void main()
{
    printf("the file is %s\n", __FILE__);
    printf("the line is %d\n", __LINE__);
}

/*
the file is aa.c
the line is 14
*/

上面如果用c89编译如gcc main.c -std=c89就会报错aa.c:12:2: error: #error not above c99
gcc main.c -std=c99就通过

 

原文地址http://daileinote.com/computer/c_base/10

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值