linux c预处理器

原文地址http://www.freecls.com/a/2712/26

#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就通过


总结

1.本文对linux c预处理器做简单的介绍,如果有疑问可以给我留言
2.lua的版本为5.1,运行环境centos7 64位
3.原文地址http://www.freecls.com/a/2712/26

猜你喜欢

转载自blog.csdn.net/freecls/article/details/80343490