1

Possible Duplicate:
C/C++ line number

Hi,

I have a simple error manager class that other classes use to report errors which are then printed out to a log file for later examination. I can print out the description and give it error codes. What I would also like, is for it to record the file name and line number where the error was recorded (automatically, rather than me writing it every time). Any way to do that? I know it come be done because I have seen it, I just can't find the solution - probably due to incorrect search terms.

Thanks!

Community
  • 1
  • 1
Samaursa
  • 16,527
  • 21
  • 89
  • 160

2 Answers2

9

As James McNellis said, use the __FILE__ and __LINE__ macros. Note that these are macros, and if you simply use them in your error handling method, they will only tell you where that error handling method is defined. You'll need to use them in another macro if you don't want to spread them around the code. Something like this:

void my_error_handler(const char* file, int line, const char* message) {
    // ...
}

#define ERROR(MESSAGE) my_error_handler(__FILE__, __LINE__, MESSAGE)

Then you can use it in your code:

if (1 == 2) {
    ERROR("Something went wrong.");
}
Rasmus Kaj
  • 4,224
  • 1
  • 20
  • 23
6

Yes, you can use the __FILE__ and __LINE__ macros, which expand to the file name and line number, respectively.

James McNellis
  • 348,265
  • 75
  • 913
  • 977