I wanna know if there is any way to know where the function currently in execution was called, this is, in what file and line.
I'm using C language, and I'm looking for something similar to __FUNCTION__, __LINE__ or __FILE__ macros.
Rename your function
void Function(param1)
{
}
to
void Function_debug(param1, char * file, char * func, unsigned long line)
{
}
Then #define a macro like this:
#define Function(param1) Function_debug(param1, __FILE__, __FUNCTION__, __LINE__)
There's nothing in C itself that would give you this information. You could either trace the information yourself (upon entry/exit) or rely on platform specific APIs to walk the call stack and determine the calling function, but not much more.
__FILE__, __LINE__ etc are preprocessor macros which can easily be expanded to the correct value at compile time. A function may get called from many possible places, so that can't be done via the preprocessor. Finding out the caller's name would be very difficult; it involves walking the stack and matching addresses to symbols.
If you can live with a small hack, this might work (untested):
/* Add a called argument to your function */
void _myFunction(char *caller, int more_args)
/* And define a macro that adds it automagically */
#define myFunction(a) _myFunction(__FUNCTION__, a)
There isn't anything that is supported in all implementations that will do what you want. I have occasionally found myself in the same situation, where I needed to track callers for a few methods and did something like the following:
#ifdef TRACKBACK
int foo(int arg1, int arg2, const char * file, int line)
{
SEND_TO_LOG("foo", file, line);
#else
int foo(int arg1, int arg2)
{
#endif
...
...
Of course, it makes for a bit of a headache at the calling end, so you'll want to do something like:
#ifdef TRACKBACK
#define TRACKING, __FILE__, __LINE__
#else
#define TRACKING
#endif
Then the call:
foo(arg1, arg2 TRACKING); //note the lack of the comma
It does the trick when all else fails.
If you need to know it at runtime, I don't think it's possible.
If you need to know it at debugtime, you can place a breakpoint on the function you want, and then, using GDB (using bt command) or Vistual Studio's debugger, inspect the current STACK TRACE.
This is actually a bit more complicated to do. Your best bet is to get a backtrace on a debugger, or find something similar to pstack for your platform. The manual way would involve traversing the call stack and using debug symbols to translate that to files and lines.
You can use logs .
#define BEGIN_FUNC(X,Y,Z) printf("Function %s Entered at line %d from file %s",X,Z,Y)
#define END_FUNC(X) printf("Function %s Exited at line %d from file %s",X,Z,Y)
foo()
{
BEGIN_FUNC(__func__,__FILE__,__LINE__);
//Your code here
END_FUNC(__func___FILE__,__LINE__);
}
OR
Use bt in gdb. I call it backtrace.
Related
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?
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
I'm trying to create transparent debug prtinf functions into OpenCL kernels that:
Do not pollute the code (can be called from max one line).
Compile away should the designated preprocessor condition prove to be untrue.
Problem is, that printf is a variadic function and I cannot wrap it in a variadic macro, since OpenCL kernel language (C99 derivate) does not support variadic macros.
#if DEBUG_CONDITION
printf("Any int %d\n",i);
#endif
Would work but would quickly render the code unreadable.
if(DEBUG_CONDITION) printf("Any int %d\n",i);
This would also work, but would require me to enable the printf pragmas, because the functions need are actually referenced in the code, even though I know they will be compiled away. (From OpenCL 2.0 on, printf will have defined sync properties, and one cannot know for sure whether the sync semantics are introduced into the binary prior to actually removing the functions or not.)
PRINTF("Any int %d\n",i);
I'm looking for something like this (or similar) that looks nice, but can fully neglect the referencing of prtintf alltogether.
As Kerrek SB has already suggested in his comment:
#if DEBUG_CONDITION
#define PRINTF(args) printf args
#else
#define PRINTF(args)
#fi
and use it as
PRINTF(("Debugging i: %d", i ));
Thanks to the double paranthesis it's no variadic macro.
If you can't use variadic macros then why not a variadic function (which is part of the C standard)
#ifdef NDEBUG
inline int debug_print(char *fmt, ...)
{}
#else
int debug_print(char *fmt, ...)
{
/* implement this I'm too lazy */
}
#endif
This results in an extra function call as opposed to a macro (though perhaps it can be inlined) but this shouldn't matter as it only happens when you are calling a debug statement (so who cares about the performance then)
It seems that for printf-style debugging people always use preprocessor macros. Is there anything wrong with a solution similar to this one?
void debug(char *msg) {
#ifdef DEBUG
printf("%s", msg);
#endif
}
Usually so that they can do something like this:
#define DEBUG(MSG) printf("[%s:%i] %s\n", __FILE__, __LINE__, (MSG))
Since it's so useful to have the exact source of a debug message right there in the log, this is a pretty common pattern. But if you used a function, like so:
void DEBUG(const char *MSG) {
printf("[%s:%i] %s\n", __FILE__, __LINE__, (MSG));
}
Then you'd only ever get to see the filename and line number corresponding to the printf() call in DEBUG(), and never those of the code that called DEBUG().
1) Your code will break if msg is %d or such, because printf expects a format string. printf("%s", msg); is better.
2) Not really. Macros are overused unless you're micro-optimizing (e.g. for code size). Functions are easier to debug with since you can do stuff like stop in debug in your debugger. There's a zillion other things that are tricky with macros. See http://www.brainbell.com/tutors/c/Advice_and_Warnings_for_C/Macros_and_Miscellaneous_Pitfalls.html
3) As #Jonathan Grynspan pointed out - the macro form is easier to use with FILE , LINE . In my opinion developers like taking shortcuts in typing that make their code harder to maintain for others later, and ironically harder to debug themselves later. Best practice IMO: type extra, make your code easy to debug and easy to run in a debugger, and use a function with signature debug(const char* msg, const char* FILE_LOC, unsigned LINE_NUMBER)
If one uses a DEBUG macro, then changing a single #define statement or compilation option and recompiling can make all of the debug code vanish from the executable. By contrast, if one uses a DEBUG() function, then every invocation will generate code to call the function, whether or not the function itself does anything.
As well as the use of __FILE__, __LINE__, you should also compare the following:
#ifdef NDEBUG
#define DEBUG_PRINT(...) ((void)0)
#else
#define DEBUG_PRINT(...) printf(__VA_ARGS__)
#endif
Against your function:
void debug(const char* msg) {
#ifndef NDEBUG
printf("%s", msg);
#endif
}
With the macro, I can write:
DEBUG_PRINT("Expected %d, got %d\n", correct_value, result);
With the function, I have to go to some effort to construct one or more strings using my integers, and call the function one or more times. In release mode the function does nothing, so the string is unused. The optimizer might manage to eliminate the code to construct it, or then again it might not. With the macro there's no doubt.
That said, you could write your debug function to do the right thing with varargs. But your function as written will hit this problem eventually, and you'll have to add a debugf.
What MACRO can be used to switch off printf statements, rather than removing them all for deployment builds, I just want to switch them off, skip them, ignore them.
EDIT: I personally use gcc, but code is part of a larger project which will be compiled on a Panda board running Ubuntu.
Not exactly what you ask for, but I use this construct in my code for debug output when I do not have a proper logging system handy:
#if 1
#define SPAM(a) printf a
#else
#define SPAM(a) (void)0
#endif
So I can do this all over my code
SPAM(("foo: %d\n", 42));
and then disable all of them by changing 1 to 0 in #if above.
But if you have variadic macro support in all compilers that you write code for, then you may go for other answers and just redefine printf. (That being said, I find it useful to distinct debugging prints from regular ones in code — using a different function name helps readability.)
Note that you also can redirect stdout to the /dev/null, but I assume that you want to get rid from runtime overhead as well.
#ifdef IGNORE_PRINTF
#define printf(fmt, ...) (0)
#endif
See also C #define macro for debug printing which discusses some important issues closely related to this.
Two options, either:
#define printf(...)
(requires C99 variadic macro parameters), you need to put it in some common header file which is never included before stdio.h, if there is one..
Or you can tell the linker to link it to something else, in GCC you would define
int wrap_printf(void) {return 0;}
and link using
--wrap printf
All that said, you should probably not be using printf for printing debug output, but rather a macro or utility function (which in turn can use printf if you'd like) which you have better control over.
Hope that helps.
If you want to avoid the potential warning that Jonathan's answer may give you and if you don't mind an empty call to printf you could also do something like
#define printf(...) printf("")
This works because C macros are not recursive. The expanded printf("") will just be left as such.
Another variant (since you are using gcc) would be something like
inline int ignore_printf(char const*, ...)
__attribute__ ((format (printf, 1, 2)));
inline int ignore_printf(char const*, ...) { return 0; }
#define printf ignore_printf
and in one compilation unit
int ignore_printf(char const*, ...)
I use to prefix the debug printf()s (not all of them) with PDEB.
For the debug builds, I compile with -DPDEB= (nothing)
For the release builds, I compile with -DPDEB="0&&" or -DPDEB="0 && "
That way, the following code (test.c):
#include <stdio.h>
void main(void) {
printf("normal print\n");
PDEB printf("debug print\n");
}
outputs:
either (in release mode):
normal print
either (in debug mode):
normal print
debug print
Ideally, one could aim for turning the PDEB into the "//" (comments mark), except that this is not possible under the standard pre-/processing chain.
Another possibility would be something like freopen("/dev/null", "w", stdout);
This doesn't exactly disable printf though -- it's roughly equivalent to running your program with stdout redirected to /dev/null, like: ./myprog > /dev/null at the shell prompt.
I included #define printf // in common header file. It will suppress all the printf.
Below simple function serves the purpose, I use the same.
int printf(const char *fmt, ...)
{
return (0)
}
Use this macro to enable or disable the printf.
//Uncomment the following line to enable the printf function.
//#define ENABLE_PRINTF
#ifdef ENABLE_PRINTF
#define DEBUG_PRINTF(f,...) printf(f,##__VA_ARGS__)
#else
#define DEBUG_PRINTF(f,...)
#endif
Then call "DEBUG_PRINTF" instead of "printf".
For example:
DEBUG_PRINTF("Hello world: %d", whateverCount);
I have used two macros for this. The first one defines the condition to print. In this simple example we print any time the parameter is not zero. More complex expressions can be used.
The second one determines, based on the first macro, to call or not printf.
If the condition can be determined by the compiler (with the right optimization settings) no code is generated.
If the condition cannot be determined at compile time then will be at run time. One of the advantages of this method is that if printf is not going to happen then the whole printf is not evaluated avoiding many conversions to string that can happen in a complex printf statement.
#define need_to_print(flag) ((flag) != 0))
#define my_printf(debug_level, ...) \
({ \
if(need_to_print(debug_level)) \
printf(__VA_ARGS__); \
})
to use it call my_printf instead of printf and add a parameter at the beginning for the print condition.
my_printf(0, "value = %d\n", vv); //this will not print
my_printf(1, "value = %d\n", vv); //this will print
my_printf(print_debug, "value = %d\n", vv); //this will print if print_debug != 0
the ( ... ) parenthesis surrounding the macro make it a single statement.
I was wondering if there is a way of finding which function called the current function (at runtime) in C.
I know you could use __FUNCTION__ in gcc, but is there a way without using the C preprocessor?
Probably not.
Cheers
No, there isn't. C isn't a particularly introspective language - things like the name of a function (or pieces of your call stack) simply aren't available at runtime in any sane fashion.
If, for some reason, you are looking for a lot of work for very little benefit, then you can build your programs with debug symbols, and you can write stack-walking and debug symbol lookup code. Then you might be able to find this out on the fly. But be careful, because the symbols you'll see in the debug info will be decorated with type info if you've got any C++ involved.
You've tagged this post gcc, so the relevant details ARE available, however this falls into the 'not recommended' and 'not guaranteed to be the same between compiler versions' territory.
Assuming you have a function f() from which you want to know the caller.
Rename that function to f_func() and define a macro f() that prints __func__ and then calls f_func(). Example:
void
f_func()
{
do something;
}
#define f() \
do { \
printf("f called from %s\n", __func__); \
f_func(); \
} while (0)
void
a()
{
f();
}
void
b()
{
f();
}
int
main(int argc, char **argv)
{
a();
b();
return(0);
}
There's no way to get a function name in the runtime. The only way is the preprocessor but it's very limited in its capabilities.
In case you have debug information available, you could walk the stack and get the function names from the debugging information. This is, however, neither a robust nor a portable solution.
There are couple of GNU functions that allow you to get function addresses and names from backtrace - backtrace() and backtrace_symbols(), but you need to compile your binary with -rdynamic flag
NO
The short answer is NO
but with preprocessor it can be done like this
Getting the name of the calling function in C (using the preprocessor)
Assuming you have a function f() from which you want to know the caller only for debugging purpose.
Rename that function to f_func() and define a macro f() that calls a version of f that prints func and then calls f_func() when DEBUG is defined.
In the final release the information is removed by calling the real function f_func()
Example
#ifdef DEBUG
#define f(a,b,c) f_debug(a,b,c, __func__)
#else
#define f(a,b,c) f_func(a,b,c)
#endif
bool f_func(int par1, int par2, int par3)
{
do_somthing();
}
bool f_debug((int par1, int par2, int par3, const char calling_func_name[])
{
printf("f called from %s\n", calling_func_name);
f_func();
}
void a()
{
f();
}
void b()
{
f();
}
int main(int argc, char **argv)
{
a();
b();
return(0);
}
Result is:
when DEBUG is defined
f called from a
f called from b
Use the __func__ identifier. The standard (section 6.4.2.2) requires that it be present for precisely this purpose:
The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration
static const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function.
As Steve Jessop notes in a comment, this isn't part of the preprocessor as such, but an intrinsic part of the compiler.
There may well be ways of finding out this name by walking the stack and looking at debugging symbols. Cute, but insane.