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?
__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.
__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.
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.
The __LINE__ is an inbuilt Macro in C programming language, it returns current line number of the code.
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With