简体   繁体   中英

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 ?

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

__LINE__ will give you the line on which it appears, which is always line 5.

To make this work, you will need to pass in __LINE__ as a separate parameter.

#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. 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. Change your function to accept an int type for the __LINE__ macro.

I would use the macro that @Ed Heal answered with. Also, the reason you are getting "msg not declared" is that variables in macros need to be enclosed in parentheses (ie (msg) ). because there is a space between the macro's name and the parenthesis that starts the parameter list.

您可以将ERR宏:

#define ERR(msg) fprintf(stderr, "ERROR on line %d: %s\n", __LINE__, (msg))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM