Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find __FUNCTION__, __LINE__ and __FILE__ of parent function?

I just made a fool of myself: I wanted to trace the execution of a process, and in order to do this, I had written a function trace(), which contains the following line of code:

printf("%s[%s:%d], %s\n", __FUNCTION__, __FILE__, __LINE__, s_message);

I hoped to see in which function I was, what file and what line within that file, but I just saw that information of the file where I programmed that trace() function.

Is it possible, is there some #define or so, to tell the C compiler to take the mentioned macros from the parent of the calling function?

like image 720
Dominique Avatar asked Feb 09 '17 11:02

Dominique


People also ask

What is __ LINE __ in C++?

__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.

What does __ file __ mean in C?

__FILE__ This macro expands to the name of the current input file, in the form of a C string constant. This is the path by which the preprocessor opened the file, not the short name specified in ' #include ' or as the input file name argument. For example, "/usr/local/include/myheader.

Is __ file __ a string?

The __file__ variable: The updating and maintaining of this variable is the responsibility of the import system. The import system can choose to leave the variable empty when there is no semantic meaning, that is when the module/file is imported from the database. This attribute is a String.

What does __ LINE __ return?

The __LINE__ is an inbuilt Macro in C programming language, it returns current line number of the code.


2 Answers

You need to wrap it in a macro, e.g.:

void _trace(char const *function, char const *file, long line, char const *message) {
  printf("%s[%s:%ld], %s\n", function, file, line, message);
}

#define trace(message) _trace(__FUNCTION__, __FILE__, __LINE__, (message))
like image 125
Thomas Avatar answered Nov 15 '22 04:11

Thomas


As others have stated, you should have a macro for that. The reason for this is that all 3 used macros get expanded at pre-processing stage of compilation, and they will be replaced by the corresponding information, as it is encountered. That's the reason your actual output is where the trace() is implemented.

You could change your current trace() implementation to receive const char * for function name, file, and line. Then, have a macro, say mTrace, that expands to calling the initial trace function, passing exactly __FUNCTION__,__FILE__, __LINE__. Of course, your mTrace could get another parameter, the actual message you want to add, and pass it further to trace().

Hth

like image 28
George Spatacean Avatar answered Nov 15 '22 03:11

George Spatacean