C语言编译预处理

1.日志打印

#define LOG(S) do{ \

time_t t; \

struct tm* localtime; \

t = time(NULL); \

localtime = localtime(&t); \

printf(“%s [%s:%d] %s\n”,asctime(localtime),_FILE_,_LINE_,s); \

}while(0)

2.条件编译(在预处理时处理,不是在运行时处理)

扫描二维码关注公众号,回复: 2532174 查看本文章

#define A 1

int main()

{

#if(A == 1)

printf(“first\n”);

#else

printf(“second\n”);

#endif

return 0;

}

编译后只有first在程序中,second被自动删除。

3.条件编译头文件(a.h包含b.h)

a.h

#include<b.h>

b.h

int a = 1;

#include<stdio.h>

#include<a.h>

#include<b.h>

int main()

{.....}

此时编译将出错; 修改b.h添加:#ifndef _B_H_   #define _B_H_

4.#error使用(#error是自己定义的错误信息error

#ifndef A

#warning please define B

#error no define A

#endif

5.#line使用(重定义_LINE__FILE_

#line 10 “hello.c”  //当前为第一行 (执行效果:define为第10行,下面的文件名为hello.c

#define A a

6.#运算符(#后的参数转化为字符串)

#define CHAR(x) #x

Int main()

{

printf(“%s\n”,CHAR(100)); //相当于printf(“%s\n”,”100”);

}

7.##运算符(连接符)

#define NAME(n) name##n

int main()

{ int NAME(1); NAME(1) = 1; //相当于int name1;name1 = 1; }

实际应用:

#define STRUCT(type) typedef struct  _tag_##type type;struct  _tag_##type

STRUCT(student)

{ char* name;  int  age; }

定义了一个student结构体。

猜你喜欢

转载自blog.csdn.net/qq_14814909/article/details/75304411
今日推荐