Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the file name, line number and function name of a calling function - C Prog

Tags:

c

I want to create log.c file with containing info(), debug() and error() functions. These functions are working without printing file name, line number,..etc. So when I call one of this function I want to dump the file name, line number, and function name of the caller. So how do we exactly trace back? Is there a way to trace back on C or, if we use macros, how can this be done?

like image 424
sura2k Avatar asked Jan 16 '12 18:01

sura2k


People also ask

What is __ function __ in C?

(C++11) The predefined identifier __func__ is implicitly defined as a string that contains the unqualified and unadorned name of the enclosing function. __func__ is mandated by the C++ standard and is not a Microsoft extension.

Can you print a function in C?

Print Function in C, C++, and PythonPrint function is used to display content on the screen. Approach: Some characters are stored in integer value inside printf function. Printing the value as well as the count of the characters.

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.


1 Answers

I'd pass the data to the function through parameters (maybe get the help of a macro)

int info(const char *fname, int lineno, const char *fxname, ...) { /* ... */ } int debug(const char *fname, int lineno, const char *fxname, ...) { /* ... */ } int error(const char *fname, int lineno, const char *fxname, ...) { /* ... */ } 

And to call them

info(__FILE__, __LINE__, __func__, ...); debug(__FILE__, __LINE__, __func__, ...); error(__FILE__, __LINE__, __func__, ...); 

Note: __func__ is C99; gcc, in mode C89 has __FUNCTION__

like image 168
pmg Avatar answered Oct 14 '22 00:10

pmg