C/C++ 宏定义 __FILE__、__LINE__、__func__、__TIME__ 等

目录

一、用例测试环境

二、宏定义

2.1 __FILE__

2.2 __LINE__

2.3 #line

2.4 __func__ 和 __FUNCTION__

2.5 __DATE__

2.6 __TIME__

三、总结

四、参考文献


  在 C/C++ 中一些宏可以用来帮助调试或输入到 log 中,本文将整理一些常见的宏。

一、用例测试环境

   整篇文章测试用例使用到的环境如下,并不是说一定要在如下环境中才有效,只是指明下本文的测试用例环境。

   系统环境:CentOS 7,CentOS Linux release 7.6.1810 (Core)

   GCC版本:gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39)

   测试文件名: macro.c 

二、宏定义

2.1 __FILE__

  作用:表示当前源文件名,类型为字符串常量;

#include <stdio.h>

int main()
{
    printf("%s\n", __FILE__);
    return 0;
}

  输出为:

[root@bogon test-dir]# ./macro 
macro.c

2.2 __LINE__

作用:代表当前程序行的行号,类型为十进制整数常量;

#include <stdio.h>

int main()
{
    printf("%d\n", __LINE__);
    printf("%d\n", __LINE__);
    return 0;
}

输出为:

[root@bogon test-dir]# ./macro 
5
6

2.3 #line

语法:#line 行号 [“文件名”]

作用:将行号和文件名更改为指定的行号和文件名;

#include <stdio.h>

#line 100 "macro-new.c" // 更改下一行的行号和源文件名
int main()              // line 100
{
    printf("%d\n", __LINE__); // line 102
    printf("%d\n", __LINE__); // line 103
    printf("%s\n", __FILE__);
    return 0;
}

输出为:

[root@bogon test-dir]# gcc -o macro macro.c 
[root@bogon test-dir]# ./macro 
102
103
macro-new.c

2.4 __func__ 和 __FUNCTION__

作用:代表当前函数的函数名,类型为字符串常量;

#include <stdio.h>

int main()
{
    printf("%s\n", __func__);
    printf("%s\n", __FUNCTION__);
    return 0;
}

输出为:

[root@bogon test-dir]# gcc -o macro macro.c 
[root@bogon test-dir]# ./macro 
main
main

2.5 __DATE__

作用:代表日期,形式为Mmm dd yyyy 的字符串常量;

#include <stdio.h>

int main()
{
    printf("%s\n", __DATE__);
    return 0;
}

输出为:

[root@bogon test-dir]# gcc -o macro macro.c 
[root@bogon test-dir]# ./macro 
Aug  9 2020

2.6 __TIME__

作用:代表时间,hh:mm:ss 形式的字符串型常量;

#include <stdio.h>

int main()
{
    printf("%s\n", __TIME__);
    return 0;
}

输出为:

[root@bogon test-dir]# gcc -o macro macro.c 
[root@bogon test-dir]# ./macro 
11:22:58

三、总结

  在上述列举出的宏都可以在 C/C++ 中使用,当然其它语言中也有相应的宏定义。

四、参考文献

[1] https://blog.csdn.net/qq_33706673/article/details/78628202

[2] https://blog.csdn.net/hj74535099/article/details/40351743

[3] https://www.bookstack.cn/read/cppreference-language/48daaf2acafd752c.md?wd=line

  • 14
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Linux猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值