How can we know the caller function's name? - c

In the C language, __FUNCTION__ can be used to get the current function's name.
But if I define a function named a() and it is called in b(), like below:
b()
{
a();
}
Now, in the source code, there are lots of functions like b() that call a(), e.g. c(), d(), e()...
Is it possible, within a(), to add some code to detect the name of the function that called a()?
Further:
Sorry for the misleading typo. I have corrected it.
I am trying to find out which function calls a() for debugging purposes. I
don't know how you do when in the same situation?
And my code is under vxWorks, but I am not sure whether it is related to C99 or
something else.

There's nothing you can do only in a.
However, with a simple standard macro trick, you can achieve what you want, IIUC showing the name of the caller.
void a()
{
/* Your code */
}
void a_special( char const * caller_name )
{
printf( "a was called from %s", caller_name );
a();
}
#define a() a_special(__func__)
void b()
{
a();
}

You can do it with a gcc builtin.
void * __builtin_return_address(int level)
The following way should print the immediate caller of a function a().
Example:
a() {
printf ("Caller name: %pS\n", __builtin_return_address(0));
}

If you are using Linux system, you can use the backtrace() function.
See the man page for more details and a code example.

Try this:
void a(<all param declarations to a()>);
#ifdef DEBUG
# define a(<all params to a()>) a_debug(<all params a()>, __FUNCTION__)
void a_debug(<all params to a()>, const char * calledby);
#endif
void b(void)
{
a(<all values to a()>);
}
#ifdef DEBUG
# undef a
#endif
void a(<all param declarations to a()>)
{
printf("'%s' called\n", __FUNCTION__);
}
#ifdef DEBUG
void a_debug(<all param declarations to a()>, const char * calledby)
{
printf("'%s' calledby '%s'", __FUNCTION__, calledby);
a(<all params to a()>);
}
#endif
If for example <all param declarations to a()> is int i, double d, void * p then <all params to a()> is i, d, p.
Or (less evil ;->> - but more code modding, as each call to a() needs to be touched):
void a((<all params of normal a()>
#ifdef DEBUG
, const char * calledby
#endif
);
void a((<all params of normal a()>
#ifdef DEBUG
, const char * calledby
#endif
)
{
#ifdef DEBUG
printf("'%s' calledby '%s', __FUNCTION__, calledby);
#endif
...
}
...
void b(void)
{
a(<all params of normal a()>
#ifdef DEBUG
, __FUNC__
#endif
);
}
__FUNCTION__ is available on GCC (at least?), if using a different C99 compiler replace it with __func__.

Refer: https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
A backtrace is a list of the function calls that are currently active
in a thread. The usual way to inspect a backtrace of a program is to
use an external debugger such as gdb. However, sometimes it is useful
to obtain a backtrace programmatically from within a program, e.g.,
for the purposes of logging or diagnostics.
The header file execinfo.h declares three functions that obtain and
manipulate backtraces of the current thread.

If you're only after knowing where you were for logging/debug purposes you can use a macro to avoid __func__ giving the name of your logging/debug function but of the function calling it.
Being in a macro will not result in a change to __func__ but will "feel" like using a function.
e.g.
#define LOG(s, data...) log("%s: "s, __function__, ## data)

If your platform is Windows, you may use this: walking the callstack

You can tag each function that calls a() with an integer identifier which is passed to a() as a parameter and then use a switch-case construct in a() to tell which function has invoked a().A printf() would tell which function invoked a() depending on the integer identifier value if you use that as an argument to a switch-case construct in a()
#include<stdio.h>
void a(int);
void b();
void c();
void d();
int main(void)
{
b();
c();
d();
}
void b()
{
int x=1;
a(x);
}
void c()
{
int x=2;
a(x);
}
void d()
{
int x=3;
a(x);
}
void a(int x)
{
switch(x)
{
case 1:
printf("b called me\n");
break;
case 2:
printf("c called me\n");
break;
case 3:
printf("d called me\n");
}
}

If the function in question is in a different c file, you can do
#define name_of_function(...) \
printf("Function %s is parent\n", __FUNCTION__); \
name_of_function(__VA_ARGS__);
And at the top of the c file it lives in
#ifdef name_of_function
#undef name_of_function
#endif
If they're in the same file, you can wrap the function definition in the second macro, then redefine the first macro at the end.
It's not terribly extensible because you can't generate new defines from other defines, but if you're trying to track down parents for a particular function it works without any nonsense.
https://godbolt.org/z/f2jKOm

#include <stdio.h>
#include <stdlib.h>
#define FUNCTION_NAME(FUNCTION) printf("FUNCTION=%s \r\n", #FUNCTION);
int a() {
printf("A function call");
}
int b() {
printf("B function call");
}
int main(){
FUNCTION_NAME(a);
FUNCTION_NAME(b);
return 0;
}

Related

How to fix macro #ifdef for conditional code?

I have a method
int someMethod(int arg1, int arg2)
{
//method body
}
and I have a macro defined say _MACRO for the same method so as to execute it based on the condition.
#ifdef _MACRO
int someMethod(int arg1, int agr2)
{
//method body
}
#endif
I am using this someMethod in say someAnotherMethod(int arg1, int arg2)
int someAnotherMethod(int arg1, int arg2)
{
//othercode
#ifdef __MACRO
someMethod(int arg1, int agr2);
//othercode
}
I get an error for the same in someAnotherMethod().
error C4100: 'arg1' : unreferenced formal parameter
Can anyone explain this thing and provide an alternative approach?
The error you’re getting has been elevated from a warning due to some compiler flag. And you’re getting the warning because, when __MACRO is undefined, your someAnotherMethod function has unused parameters.
The conventional way of silencing this warning is to cast the parameter to void, thereby using it.
Something else, your macro name is invalid, you mustn’t use a double underscore, or a leading underscore followed by a capital letter. This notation is reserved for the C implementation.
Instead, use YOUR_LIBRARY_NAME_MACRO as a naming convention.
int someAnotherMethod(int arg1, int arg2) {
# ifdef LIB_MACRO
someMethod(int arg1, int agr2);
# else
(void) arg1;
(void) arg2;
# endif
}
This is sometimes hidden behind a macro:
#define UNUSED(x) (void) (x)
…
int someAnotherMethod(int arg1, int arg2) {
…
UNUSED(arg1);
…
}
I'm hesitant to present you with this solution as it's the ugliest hack ever.
Context : I'm working with a very old C compiler that has a lot of quirks, one of which is that the warnings about unused parameters or variables can happen at any given steps of the optimization process. So, for example, sometimes you get a warning that a certain variable is unused, but truly, it has just been optimized away.
The old codebase is also littered by #ifdef, so I've encountered your problem more than once.
The hack
suppresswarning.h
extern long SuppressWarning;
#define SUPPRESS_WARNING(p) (SuppressWarning += (uintptr_t)&(p))
suppresswarning.c
long SupressWarning;
YourFile.c
#include "suppresswarning.h"
int someAnotherMethod(int arg1, int arg2)
{
//othercode
#ifdef __MACRO
someMethod(arg1, agr2);
//othercode
#else
SUPPRESS_WARNING(arg1);
SUPPRESS_WARNING(arg2);
#endif
}
The SUPPRESS_WARNING macro, essentially, prevents the compiler from optimizing the variable away. This has the added value to be clear for any new programmer reading the code ; SUPPRESS_WARNING suppresses a warning.
This hack doesn't necessarly require to add a translation unit. Most projects have miscellaneous units for debugging or for utility functions ; this can be put there instead.
Alternative:
#define FOO (FOO1)
enum Foo {
FOO1,
FOO2,
FOO3
};
int foo1(void);
int foo2(void);
int foo3(void);
int foo(void)
{
switch (FOO) {
case FOO1:
return foo1();
case FOO2:
return foo2();
case FOO3:
return foo3();
default:
return -1;
}
}
int foo1(void)
{
return 1;
}
int foo2(void)
{
return 2;
}
int foo3(void)
{
return 3;
}
The benefit of this is that the compiler compiles all the code, so you can check if there are any errors in the code, which with the preprocessor you don't get.
Basically the preprocessor #if and company are useful only for using features that may not be available, but if a feature is available, then prefer if or switch.
int someAnotherMethod(
#ifdef __XYZ
int arg1,
#else
int,
#endif
int arg2)
{
//othercode
#ifdef __XYZ
someMethod(int arg1, int agr2);
#endif
//othercode
}
This worked fine for both the arguments.

Function visibility in C : make function visible and callable through macro only (MSVC compiler)

I would like to make function to be callable (e.g. exposed) to the rest of the library through the macro only, to prevent accidental undesired side effects.
Why? This is because I have a variadic function, which could be called from another variadic function and that way I would like to add NULL sentinel to the call, using macro, thus making access to va_list much easier and prevent undefined behaviour. There are also other handy scenarios, where this could really be helplful.
An example :
test.h
void _func(char *dummy, ...);
//I would like to make sure that rest of the library
//only calls _func through this macro
#define func(dummy, ...) _func(dummy, __VA_ARGS__, NULL)
test.c
//Implementation of the _func function
static void _func(char *dummy, ...) {
//body goes here...
}
main.c
int main(int argc, char *argv[]) {
//This should not be allowed by compiler
_func("dummy", "arg1");
//This should be allowed by compiler, but since definition
//of _func is static in test.c file, compiler is not happy anyway
//LNK2001 unresolved external symbol __func
func("dummy", "arg1");
return 0;
}
I've already tried with #define and #undef compiler directives to somehow force this scenario, but no avail. Is this even possible in C?
You can shadow the function with a macro:
void _func(char *dummy, ...);
#define _func(...) error_use_the_macro_func_instead_of_calling__func_directly
// Always use the macro "func" instead of calling "_func" directly.
#define func(dummy, ...) (_func)(dummy, __VA_ARGS__, NULL)
Notice the parentheses around _func in the macro. This prevents the _func from being recognized as a function-like macro and gives the macro access to the function. If somebody tries to call _func directly, they get
error C2065: 'error_use_the_macro_func_instead_of_calling__func_directly': undeclared identifier
This "macro shadowing" technique has the advantage of being usable in expression contexts:
for (int i = 0; i < 5; func("incrementing i", ++i)) { ... }
or if we change the situation slightly and give _func a return value:
int _func(char *dummy, ...);
#define _func(...) error_use_the_macro_func_instead_of_calling__func_directly
// Always use the macro "func" instead of calling "_func" directly.
#define func(dummy, ...) (_func)(dummy, __VA_ARGS__, NULL)
then this allows you to do things like
int i = func("hello", 2) * func("there", 3);
Maybe you can scope the visibility of the private function? Here's a snippet to illustrate what I mean. Not pretty, but it may work for you(no MSVC to test with here)
#define func(a, b) do { \
extern void private_func(int , int );\
private_func(a, b);\
} while (0)
void foo(void)
{
func(1, 2);
private_func(3, 4);
}
What #Bjorn A. has written in the post above, actually solves my problem as compiler gets angry with the message : '_func': redefinition; different basic types if I try to call _func directly.
Here is the adopted example :
test.h
#define func(dummy, ...) do { \
extern void _func(char *, ...);\
_func(dummy, __VA_ARGS__, NULL);\
} while (0)
test.c
//Implementation of the _func function
//static has to be omitted here, but it doesn't matter
void _func(char *dummy, ...) {
//body goes here...
}
main.c
int main(int argc, char *argv[]) {
//'_func': redefinition; different basic types
//if we try to call _func directly
_func("dummy", "arg1");
//this is ok
func("dummy", "arg1");
func("dummy2", "arg2");
return 0;
}
EDIT : Actually, #Raymond Chen has proposed much better solution with function shadowing - idea is to enclose the function name with parentheses to stop preprocessor from expanding it. More info about that here.
Here is the final (hopefully) solution that works like a charm :
test.h
void _func(char *dummy, ...);
#define _func(...) error_use_the_macro_func_instead_of_calling__func_directly
#define func(dummy, ...) (_func)(dummy, __VA_ARGS__, NULL)
test.c
//Notice the _func is enclosed with parentheses here
void (_func)(char *dummy, ...) {
//body goes here...
}
main.c
int main(int argc, char *argv[]) {
//C2065 'error_use_the_macro_func_instead_of_calling__func_directly': undeclared identifier
//if we try to call _func directly
_func("dummy", "arg1");
//this is ok
func("dummy", "arg1");
func("dummy2", "arg2");
return 0;
}
Many thanks! Cheers!

c stringification and __function__

I am trying to add a c macro which compiles a local variable
which is initialized to the function name..
for example.
void foo (void)
{
stubmacro;
}
void bar (void)
{
stubmacro;
}
would essentially compile as:
void foo (void)
{
char*function_name="foo";
}
void bar (void)
{
char*function_name="bar";
}
I've always had a difficult time with C preprocessor macros,
especially when it comes to stringification
the macro uses the prefined FUNCTION ..
#define stubmacro char*function_name=##_FUNCTION__
Anyway, my stubmacro macro is wrong, and I' would love some help
on it
Just use __func__, this is a predefined string that does what you need:
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.
You can refer the below code:
#include <stdio.h>
#define stubmacro char *func = __func__;
void foo (void)
{
stubmacro;
printf("foo = %s\n", func);
}
void bar (void)
{
stubmacro;
printf("bar = %s\n", func);
}
int main(void)
{
foo();
bar();
return 0;
}
The output would be:
foo = foo
bar = bar
Here __func__ is a macro that will be replaced with the function name in which it is used
Also instead using a macro for the function name you can directly print in the function like below
void foo (void)
{
printf("foo = %s\n", __func__);
}

Using #define to force call a function

Lets say I have the following code:
void test(void)
{
#define INIT_DONE
//General initialization stuff
}
void test2(void)
{
#ifndef INIT_DONE
#error "Call function test() first!"
#endif
// Specific initialization stuff
}
And then in main() I call these function as follows:
int main(void)
{
test();
test2();
}
And even though I call test() first, and #define INIT_DONE I still get:
"Call function test() first!"
error on the compiler.
So, how can I achieve, that the function test() has to get called first before any other functions. I could do this with some global boolean variable or something, but I am hoping there is a preprocessor way of doing it. Is there?
The preprocessor runs before your code is handled to the compiler. Everything it does happens before your code runs. The prepocessor has no notion of functions or variables, it just copies input to output and expands macros in between (it actually does some more stuff but that's unimportant). For your code, the preprocessor essentially sees this:
gibberish
#define INIT_DONE
// comment
more gibberish
#ifndef INIT_DONE
#error "Call function test() first!"
#endif
// another comment
even more gibberish
The preprocessor walks through that and first sees #define INIT_DONE, so it defines the macro INIT_DONE to 1; every future appearance of INIT_DONE will be replaced by 1 discarded before the compiler sees the code. Then it sees #ifndef INIT_DONE, but INIT_DONE is already defined so it skips the following bit.
The point is that at no point the preprocessor cares about what is being executed. To do what you want to, use something like this:
#include <assert.h>
/* only visible in the source code form where test() and test2() are defined */
static int init_done = 0;
void test(void)
{
init_done = 1;
/* ... */
}
void test2(void)
{
assert(init_done);
/* ... */
}
There is generally no way to do this in the preprocessor since the preprocessor runs before your program runs. You can also leave these checks out and just emphasize that initialization needs to be done in your documentation. Another approach is to not require initialization by the programmer at all, that is useful depending on the circumstances:
static int init_done = 0;
/* same initialization function as before */
void test(void)
{
init_done = 1;
/* ... */
}
void test2(void)
{
if (!init_done)
test();
/* ... */
}

Fun with C macros

Let's say I have a function macro in C called FOO. There are also two macros called BAR1 and BAR2, which are basically two flavors of the same macro. I'd like to write a macro BAR such that it expands to BAR1 in functions which invoke FOO somewhere before the use of BAR and to BAR2 otherwise. So for example:
void func1(void)
{
FOO();
...
BAR();
}
would be equivalent to
void func1(void)
{
FOO();
...
BAR1();
}
while this function:
void func2(void)
{
BAR();
}
would be equivalent to
void func2(void)
{
BAR2();
}
I'd like to avoid introducing global variables or doing additional checks at runtime. Is this even possible?
Short answer: NO. The C precompiler knows nothing about function limits, so even if you managed to modify the BAR macro as you want it, that would not be limited to the current function anyway.
Now, if you are willing, you can add some checks to the BAR macro. And those checks can be written to be resolved at compile time, so no runtime overhead results.
For example:
extern char _sentinel_[2];
#define FOO() char _sentinel_;
#define BAR() if (sizeof(_sentinel_) == 1) BAR1() else BAR2()
The trick is that the look up of variable _sentinel_ will resolve the global variable or the local one, depending on the use of FOO(). And since the condition in the if is a compiler constant, the compiler will optimize out the other branch.
My attempted hack at using gotos failed because when FOO() isn't used, the jump label is missing for BAR(). But, fear not, I've come up with an even more gross hack.
You can use #includes instead of a macro for FOO() and BAR(). This will allow you absolute control on how the code gets expanded.
/* FOO file */
#define BAR_IS_BAR2
/* whatever code FOO needs to do */
/* BAR file */
#ifdef BAR_IS_BAR2
BAR2();
#undef BAR_IS_BAR2
#else
BAR1();
#endif
/*...in you source code...*/
void func1 () {
#include "FOO"
/*...*/
#include "BAR"
}
void func2 () {
#include "BAR"
}

Resources