In the sake of debugging purposes, can I get the line number in C/C++ compilers? (standard way or specific ways for certain compilers)
e.g
if(!Logical)
printf("Not logical value at line number %d \n",LineNumber);
// How to get LineNumber without writing it by my hand?(dynamic compilation)
Checkout
__FILE__
and__LINE__
macrosUse
__LINE__
(that's double-underscore LINE double-underscore), the preprocessor will replace it with the line number on which it is encountered.Since i'm also facing this problem now and i cannot add an answer to a different but also valid question asked here, i'll provide an example solution for the problem of: getting only the line number of where the function has been called in C++ using templates.
Background: in C++ one can use non-type integer values as a template argument. This is different than the typical usage of data types as template arguments. So the idea is to use such integer values for a function call.
Output:
One thing to mention here is that in C++11 Standard it's possible to give default template values for functions using template. In pre C++11 default values for non-type arguments seem to only work for class template arguments. Thus, in C++11, there would be no need to have duplicate function definitions as above. In C++11 its also valid to have const char* template arguments but its not possible to use them with literals like
__FILE__
or__func__
as mentioned here.So in the end if you're using C++ or C++11 this might be a very interesting alternative than using macro's to get the calling line.
Try
__FILE__
and__LINE__
.You might also find
__DATE__
and__TIME__
useful.Though unless you have to debug a program on the clientside and thus need to log these informations you should use normal debugging.
You should use the preprocessor macro
__LINE__
and__FILE__
. They are predefined macros and part of the C/C++ standard. During preprocessing, they are replaced respectively by a constant string holding an integer representing the current line number and by the current file name.Others preprocessor variables :
__func__
: function name (this is part of C99, not all C++ compilers support it)__DATE__
: a string of form "Mmm dd yyyy"__TIME__
: a string of form "hh:mm:ss"Your code will be :
As part of the C++ standard there exists some pre-defined macros that you can use. Section 16.8 of the C++ standard defines amongst other things, the
__LINE__
macro.So your code would be: