C语言__LINE__实现原理

在test.c中写如下代码:

  1 #include <stdio.h>

  2 

  3 int main()

  4 {

  5     printf("line:%d\n", __LINE__);

  6     return 0;

  7 }

使用gcc编译 gcc -o test test.c

执行 ./test

结果 line:5

__LINE__ 是通过什么方式知道自己在第5行呢?

使用命令 gcc -E test.c -o test.i 进行预处理

查看test.i的最后几行代码如下:

535 # 412 "/usr/include/stdio.h" 2 3 4

536 # 2 "test.c" 2

537 

538 int main()

539 {

540     printf("line:%d\n", 5);

541     return 0;

542 }

由此可见:在预处理阶段,__LINE__ 会被替换成自己所在行的行号。

猜你喜欢

转载自www.cnblogs.com/jiexianzhu/p/10274455.html
今日推荐