18

I have a macro that passes the line number and file name to an error handler:

#define SYSTEM_FAILURE (error_code, comment) \
   System_Failure((error_code), (comment), __LINE__, __FILE__);

How will the __LINE__ be resolved when used inside an inlined function?

file.h:
inline int divide(int x, int y)
{
    if (y == 0)
    {
        SYSTEM_FAILURE(ENUM_DIVIDE_BY_ZERO, "divide by zero error");
    }
    return x/y;
}

Will __LINE__ contain the line number within the header file, or the line number of the source file where the inline function is called (assuming compiler does a "paste" in the source code)?

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • 2
    Can't try it out as behavior may differ on compilers and may not be what the standard states. – Thomas Matthews Jun 26 '12 at 19:07
  • 4
    Downvoters: Why the downvote? The question arises from using C, inline functions and macros in an embedded system. – Thomas Matthews Jun 26 '12 at 19:09
  • 1
    @Thomas, testing this on your own compiler and including the results in your question (thus making it more like `my preprocessor does this, is it standard?`) would have (and still can) neuter many of the downvotes. – Frédéric Hamidi Jun 26 '12 at 19:16

3 Answers3

23

In C and C++, macros aren't (for the most part) evaluated with any knowledge of the actual code and are processed before the code (hence the name "preprocessor"). Therefore, __FILE__ would evaluate to "file.h", and __LINE__ would evaluate to the line number corresponding to the line on which SYSTEM_FAILURE appears in file.h.

Eric Finn
  • 8,629
  • 3
  • 33
  • 42
7

Since macros are replaced by their definitions before compilation, the __LINE__ will contain the actual line of the file in which you used the macro. Inlining will not affect this behaviour at all.

mfontanini
  • 21,410
  • 4
  • 65
  • 73
6

__LINE__ will be the line of the header file since the preprocessor will evaluate it before the compiler will ever see it.

Dave Rager
  • 8,002
  • 3
  • 33
  • 52