3

Is there any way to get the source code line number in C code in run time? The thought behind it is, suppose a software is made in plain C language. the .exe file is distributed to a user who knows nothing about C. Now if there is any error, the user can see the line number and report the error to the manufacturer so that the debugging can be done at manufacturer site. I just to debug the run time errors and get the corresponding line numbers in the source code while running it. I am a beginner in these stuffs.

  • Is it not good enough to compile with debug symbols and run code in a debugger like gdb? – ad absurdum Jan 31 '17 at 03:09
  • That's a dup that answers your specific question. But as pointed out by the first comment, the better way to debug is to use a debugger. – kaylum Jan 31 '17 at 03:12
  • I am asking for line numbers during run time. Could you please explain? I am a beginner in coding – Debasmita Bhoumik Jan 31 '17 at 03:13
  • Read the link to the duplicate questions. It explains that. Did you read it? – kaylum Jan 31 '17 at 03:14
  • the question is edited now.. previously i think i could not explain it properly – Debasmita Bhoumik Jan 31 '17 at 03:16
  • Well, either your program will print an error message which can include the line number as described by the linked answer or the program crashes in which case you get get it to dump a core to be sent back to you for analysis. – kaylum Jan 31 '17 at 03:19

3 Answers3

4

If you are using the GCC compiler, you can use the Standard Predefined Macro - __LINE__ as a line number placeholder.

The compiler will fill in the line number while compiling.

Eg :-

printf("%d",__LINE__);

Surojit
  • 1,282
  • 14
  • 26
2

You can use the built-in macros __LINE__ and __FILE__, which always expand to the current file name and line number.

#include <stdio.h>

int main(int argc, char *argv[])
{
    if(argc<2)
    {
        printf("Error: invalid arguments (%s:%d)\n", __FILE__, __LINE__);
        return 0;
    }
    printf("You said: %s\n", argv[1]);
    return 0;
}
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
2

Use gdb instead. But I guess it will work:

  if(someThingsWrong())
    printf("wrong at line number %d in file %s\n", __LINE__, __FILE__);
twodee
  • 606
  • 5
  • 24