[英]get code line with __LINE__
I tried to print the line number of the current code by using: 我尝试使用以下方法打印当前代码的行号:
#include <stdio.h>
void err (char *msg)
{
printf ("%s : %d" , msg , __LINE__);
}
int main ( int argc , char **argv )
{
ERR ("fail..");
return 0;
}
But i always get the wrong line number , it should be 10
instead of 5
, how can i fix this ? 但我总是得到错误的行号,它应该是10
而不是5
,我该如何解决这个问题呢?
Also i tried to use some macro: 我也尝试使用一些宏:
#define ERR (msg) do { printf ("%s : %d\\n" , msg , __LINE__); } while (0)
and result in error: msg not declared
并导致错误: msg not declared
__LINE__
will give you the line on which it appears, which is always line 5. __LINE__
将显示它出现的行,它始终是第5行。
To make this work, you will need to pass in __LINE__
as a separate parameter. 要使其工作,您需要将__LINE__
作为单独的参数传递。
#include <stdio.h>
void err (char *msg, int line)
{
printf ("%s : %d" , msg , line);
}
int main ( int argc , char **argv )
{
err("fail..", __LINE__);
return 0;
}
An even better way to do this would be to define the invocation of such method as a macro , like so: 更好的方法是将这种方法的调用定义为宏 ,如下所示:
#define PRINTERR(msg) err((msg), __LINE__)
#define ERR(msg) printf("%s : %d", (msg), __LINE__)
Should do the trick. 应该做的伎俩。
You do not need the function! 你不需要这个功能!
__LINE__
gets the current line, meaning the line that it was called on. __LINE__
获取当前行,表示调用它的行。 You need to pass it as a parameter: 您需要将其作为参数传递:
ERR ("fail..", __LINE__);
Otherwise it will always be the line inside your error function, 5 in your example. 否则它将始终是您的错误函数中的行,在您的示例中为5 。 Change your function to accept an int
type for the __LINE__
macro. 更改函数以接受__LINE__
宏的int
类型。
I would use the macro that @Ed Heal answered with. 我会使用@Ed Heal回答的宏。 Also, the reason you are getting "msg not declared" is
that variables in macros need to be enclosed in parentheses (ie
另外,你得到“msg not declared”的原因是
(msg)
).
宏中的变量需要括在括号中(即
because there is a space between the macro's name and the parenthesis that starts the parameter list. 因为宏的名称和括号之间有一个空格来启动参数列表。 (msg)
)。
您可以将ERR
宏:
#define ERR(msg) fprintf(stderr, "ERROR on line %d: %s\n", __LINE__, (msg))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.