C macros __LINE__, __FILE__ and __func__

51 篇文章 0 订阅

It is possible for a C program to print the currently executing line of source code, the file of the source code, and the name of the current function. The currently executing line is available in a preprocessor variable called__LINE__:

#include <stdio.h>

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

This prints out

This is line 5.

To get the name of the file, use the preprocessor variable __FILE__:

#include <stdio.h>

int main ()
{
    printf ("This is line %d of file \"%s\".\n",
            __LINE__, __FILE__);
    return 0;
}

This prints out

This is line 6 of file "/share/websites/www.lemoda.net/c/line-file-func/file.c".

C99 (the most recent version of the C language, at the time of writing) introduced another macro called__func__ which also names the function in use:

#include <stdio.h>

#define BLURT printf ("This is line %d of file %s (function %s)\n",\
                      __LINE__, __FILE__, __func__)

void silly_function ()
{
    BLURT;
}

int main ()
{
    BLURT;
    silly_function ();
    return 0;
}

This prints out

This is line 13 of file /share/websites/www.lemoda.net/c/line-file-func/func.c (function main)
This is line 8 of file /share/websites/www.lemoda.net/c/line-file-func/func.c (function silly_function)

You can change the values used for __FILE__ and __LINE__ using a line directive, which is a preprocessor command of the form

#line 20 "some-file"

which tells the C compiler that the next line after the line directive is line 20 ofsome-file.

#include <stdio.h>

#define BLURT printf ("This is line %d of file \"%s\" (function <%s>)\n",\
                      __LINE__, __FILE__, __func__)

#line 99 "grody-to-the-max"
void silly_function ()
{
    BLURT;
}

#line 999 "bassetts-liquorice-allsorts"
int main ()
{
    BLURT;
    silly_function ();
    return 0;
}

This prints out

This is line 1001 of file "bassetts-liquorice-allsorts" (function <main>)
This is line 101 of file "grody-to-the-max" (function <silly_function>)

This line directive is used by facilities like "lex" and "yacc" which output C code so that error messages are related to the input file rather than the output C file.

GCC (the "Gnu Compiler Collection") also defines __FUNCTION__ and__PRETTY_FUNCTION__. These are both the same as __func__ for C. For C++,__PRETTY_FUNCTION__ is something different.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值