__FILE__:记录文件的路径加名称
__LINE__:记录文件已经被编译的行数
__DATE__:记录文件的编译日期
__TIME__:记录文件的编译时间
可以当作变量直接使用,一般用作程序调试
例子:
#include <iostream>
using namespace std;
int main()
{
cout << "File = " << __FILE__ << '\n'
<< "LINE = " << __LINE__ << '\n'
<< "DATE = " << __DATE__ << '\n'
<< "TIME = " << __TIME__
<< endl;
getchar();
}
运行结果:
File = G:/program/study/c++/test1.cpp
LINE = 17
DATE = May 27 2004
TIME = 09:59:01
利用__FILE__,__LINE__,FUNCTION__实现代码跟踪调试(linux下c语言编程 )
先看下简单的初始代码:注意其编译运行后的结果。
root@xuanfei-desktop:~/cpropram/2# cat global.h //头文件
#ifndef CLOBAL_H
#define GLOBAL_H
#include <stdio.h>
int funca(void);
int funcb(void);
#endif
root@xuanfei-desktop:~/cpropram/2# cat funca.c //函数a
#include "global.h"
int funca(void)
{
printf ("this is function\n");
return 0;
}
root@xuanfei-desktop:~/cpropram/2# cat funcb.c //函数b
#include "global.h"
int funcb(void)
{
printf ("this is function\n");
return 0;
}
root@xuanfei-desktop:~/cpropram/2# gcc -Wall funca.c funcb.c main.c //联合编译
root@xuanfei-desktop:~/cpropram/2# ./a.out //运行
this is main
this is function
this is main
this is function
this is main
相同结果很难让人看出那里出错,下面我们用用 __FILE__,__LINE__,__FUNCTION__加入代码,看看有什么区别吗.
把 __FILE__,__LINE__,__FUNCTION__加入到mail.c中
root@xuanfei-desktop:~/cpropram/2# cat main.c
#include "global.h"
int main(int argc, char **argv)
{
printf("%s(%d)-%s: this is main\n",__FILE__,__LINE__,__FUNCTION__);
funca();
printf("%s(%d)-%s: this is main\n",__FILE__,__LINE__,__FUNCTION__);
funcb();
printf("%s(%d)-%s: this is main\n",__FILE__,__LINE__,__FUNCTION__);
return 0;
}
root@xuanfei-desktop:~/cpropram/2# gcc -Wall funca.c funcb.c main.c
root@xuanfei-desktop:~/cpropram/2# ./a.out
main.c(4)-main: this is main
this is function
main.c(6)-main: this is main
this is function
main.c(8)-main: this is main
上面的结果main.c(4)-main:this is main 表示在mian.c源代码的第四行main函数里边打印出来的 this is main
那样的话就很方便的让程序员对自己的程序进行排错!
为了更方便的使用它我们可以通过在global.h代码中进行宏定义
root@xuanfei-desktop:~/cpropram/2# cat global.h
#ifndef CLOBAL_H
#define GLOBAL_H
#include <stdio.h>
int funca(void);
int funcb(void);
#define DEBUGFMT "%s(%d)-%s"
#define DEBUGARGS __FILE__,__LINE__,__FUNCTION__
#endif
root@xuanfei-desktop:~/cpropram/2# cat funca.c
#include "global.h"
int funca(void)
{
printf (DEBUGFMT " this is function\n",DEBUGARGS);
return 0;
}
root@xuanfei-desktop:~/c