Get a line of code using __LINE__

I tried to print the line number of the current code 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 it?

I also tried using a macro:

#define ERR (msg) do { printf ("%s : %d\n" , msg , __LINE__); } while (0)

and result in an error: msg not declared

+4
source share
4 answers
 #define ERR(msg) printf("%s : %d", (msg), __LINE__) 

Gotta do the trick.

You do not need a function!

+8
source

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

To do this, you need to pass __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 is to define a call to a method such as a macro, for example:

 #define PRINTERR(msg) err((msg), __LINE__) 
+10
source

__LINE__ gets the current line, which means that it was called. You need to pass it as a parameter:

 ERR ("fail..", __LINE__); 

Otherwise, it will always be a string inside your error function, 5 in your example. Modify your function to accept the int type for the __LINE__ macro.

I would use a macro answered by @Ed Heal. Also, the reason you get the msg message not declared is that the variables in the macros should be enclosed in parentheses (i.e. (msg) ). , because there is a space between the macro name and the bracket, it starts the parameter list.

+6
source

You can make an ERR macro:

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

All Articles