Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get code line with __LINE__

Tags:

c++

c

macros

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

like image 859
daisy Avatar asked Nov 29 '22 10:11

daisy


1 Answers

__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__)
like image 123
Jacob Relkin Avatar answered Dec 09 '22 22:12

Jacob Relkin