c stringification and __function__ - c

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__);
}

Related

Calling a function within another function (except main())

Let's assume I have 2 functions other than the main(), respectively func1() and func2(). Is it possible for me to call func1() in func(2) without declaring it first? Or should I use a pointer to the other function and pass it as an argument? Thanks in advance.
_"Is it possible for me to call func1() in func(2) without declaring it first?"_
It depends on compiler, but generally this will not work. (see exclusion example at bottom of answer.)
Some scenarios that illustrate:
Scenario 1: Normally will not work as function is being referenced before being declared:
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Results:
9, 15 error: implicit declaration of function 'func1' is invalid
in C99. Make sure that you include the function prototype.
Scenario 2: As all required definitions occur in order, this will compile and run without issue:
char func1(void)
{
return 1;
}
char func2(void)
{
return func1();
}
int main(void)
{
char ret = func1();
ret = func2();
return 0;
}
Results:
Compiles and runs with no problem because both functions are defined before being called (both func2() called from main() and func1() called from func1)
Scenario 3: The best way is always to pre-declare functions using prototypes either in same file before functions are called or in a header file that is #included in any source file that uses them. This clears up any potential problems, especially for those that inherit the code for maintenance:
int func1(void);
int func2(void);
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Regarding your comment:
"...a statement in my book caused confusion, I thought it might be related to a difference of the version of the C compiler in the book and I am using."
Could be: Per comment below, pre-standard C function definitions are supported by some modern compilers (eg gcc) thus would compile scenarios 1 & 2 without issue if functions complied with the default function definition; eg:
int func1(void)
int func2(void)
Here is how you do it:
void func2(int code); // forward declaration
void func1(const char* str)
{
func2(str[0]); // a call to a declared function
}
void func2(int code) // the callee
{
printf("code: %d\n", code);
}

Remove a function during compile by defining it as an empty macro

In this example code a macro is either defined or commented out by the programmer in order to remove a function from the released software.
#include <stdio.h>
#define MACRO //or omitted
#ifdef MACRO
void Function(const char* str)
{
printf("%s\n", str);
}
#else
#define Function(str)
#endif
int main(void)
{
Function("hello world");
getchar();
return 0;
}
Is there anything wrong with this?
Even though your solution works, I prefer the following approach:
#include <stdio.h>
#define MACRO //or omitted
#ifdef MACRO
#define FUNCTION(a) Function(a);
#else
#define FUNCTION(a)
#endif
#ifdef MACRO
void Function(const char* str)
{
printf("%s\n", str);
}
#endif
int main(void)
{
FUNCTION("hello world")
getchar();
return 0;
}
Note: FUNCTION is the macro, Function is the actual name of the function
This works by defining the macro FUNCTION(a) to a call to Function(const char*) when MACRO is enabled. On the other hand, when MACRO is disabled, calls to FUNCTION(a) will be defined to nothing.
I tend to prefer this method since it would be easier to abstract away the macro used to define your call from the macro defining your function definition. You might have cases where in release mode you only need to remove some of the calls to Function. In that case the definition of Function() is still required. For example:
#include <stdio.h>
#define DEBUG //or omitted
#ifdef DEBUG
#define FUNCTION(a) Function(a);
#else
#define FUNCTION(a)
#endif
void Function(const char* str)
{
printf("%s\n", str);
}
int main(void)
{
// Call function with Hello World only in debug
FUNCTION("hello world")
getchar();
// Call function with goodbye world in both debug and release
Function("goodbye world");
return 0;
}
It will work. But the entire symbol is removed this way. I prefer the following method.
#include <stdio.h>
#define MACRO 1
#if MACRO
void Function(const char* str)
{
printf("%s\n", str);
}
#else
void Function(const char *str){}
#endif
int main(void)
{
Function("hello world");
getchar();
return 0;
}
The following has changed:
The #if now compares a boolean. Your IDE is now able to find where MACRO is defined, in all cases. (right click, find definition)
You can, by changing MACRO to 2, change the entire meaning of Function. For example, a release compiled variant might contain a print to file or system log.
There will always be a symbol for Function, even if it does nothing, even in compiled code. This has the benefit that the string literals in the argument still count to the size statistics. As an embedded developer, I find this important.
Obviously, this is partly the preference of the one who crafts the code.

How to use macro for calling function?

I want to call function according to func_name string.
My code is here below:
#define MAKE_FUNCNAME func_name##hello
void call_func(void* (*func)(void))
{
func();
}
void *print_hello(void)
{
printf("print_hello called\n");
}
int main(void)
{
char func_name[30] = "print_";
call_func(MAKE_FUNCNAME);
return 0;
}
But this code doesn't work. I want code to work like call_func(print_hello). But preprocessor treated my code like call_func("print_hello"). How to use macro in C to make my exception? Or is it not possible using C?
Then problem with your code is that the value of func_name is only known at run-time.
You can however to it like this:
#define MAKE_FUNCNAME(FUNCNAME) FUNCNAME##hello
void call_func(void* (*func)(void))
{
func();
}
void *print_hello(void)
{
printf("print_hello called\n");
}
int main(void)
{
call_func(MAKE_FUNCNAME(print_));
return 0;
}
But it is not possible to use a string value within macro parameters like in your code snippet.
If you want to get call functions with their names using string values you can use a table to store function pointer with function names like this:
struct {
const char *name;
void (*ptr)(void);
};
You can use an array of this structure to find out the function pointer at run-time using a string value. This is the most common solution to using run-time strings to call functions using their names.
You can't do that. The value of func_name is known at run-time (even though it is a const char *), while you want to determine what to call at precompile-time. You should turn your cpp macro into something different (such as an if/switch statement or using an indirection).
Maybe you could have a look to dlsym().
Not sure I really understand the question, but if you want to "build" the function name at runtime and then call the corresponding function, it should be possible with dlsym()
/* compile with: gcc example.c -ldl -rdynamic */
#include <dlfcn.h>
#include <stdio.h>
int print_hello(void)
{
return printf("hello\n");
}
int main(int argc, char *argv[])
{
const char *name = "print_hello";
if (argc == 42)
print_hello(); /* for compiler not to remove print_hello at
* compile time optimisation in this example*/
void *handle = dlopen(NULL /* self */, RTLD_NOW);
int (*f)(void) = dlsym(handle, name);
f();
return dlclose(handle);
}

How can we know the caller function's name?

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;
}

using #defines and passing functions to them

gcc 4.4.2 c89
I re-engineering some code in c89. However, I am totally confused with the code that uses the following #defines. So I created a small application that maybe I would understand more of how this is working.
From what I can gather the MODULE_API will pass a function name and call the macro MODULE_SOURCE_API and concatenate name and func. So I create a simple function called print_name and ran the code. I got the following error messages:
implicit declaration of function ‘print_name’
undefined reference to `print_name'
What would be the main reason for doing this?
#include <stdio.h>
#define MODULE_SOURCE_API(name, func) name##_##func
#define MODULE_API(func) MODULE_SOURCE_API(mod_print, func)
void MODULE_API(print_name)(const char const *name);
int main(void)
{
printf("=== Start program ===\n");
print_name("Joe bloggs");
printf("== End of program ===\n");
return 0;
}
void MODULE_API(print_name)(const char const *name)
{
printf("My name is [ %s ]\n", name);
}
Many thanks for any advice,
EDIT ====
I have just made a correction I should be calling
MODULE_API(print_name)("Joe Bloggs");
But how can I print out what will be the outcome of concatenating? And what is the reason for doing this?
Many thanks,
#define MODULE_SOURCE_API(name, func) name##_##func
#define MODULE_API(func) MODULE_SOURCE_API(mod_print, func)
void MODULE_API(print_name)(const char const *name);
That will be producing a function named mod_print_print_name instead of print_name
You can check it on gcc with the -E option.
gcc -E ak.c gives
/* ...... */
void mod_print_print_name(const char const *name);
int main(void)
{
printf("=== Start program ===\n");
print_name("Joe bloggs");
printf("== End of program ===\n");
return 0;
}
void mod_print_print_name(const char const *name)
{
printf("My name is [ %s ]\n", name);
}
You can try to manually expand the macros to understand what is going on:
void MODULE_API( print_name )( const char * name ); // the second const there is redundant
// maybe you meant 'const char * const??
=(expand MODULE_API)=>
void MODULE_SOURCE_API( mod_print, print_name )( const char* name );
=(expand MODULE_SOURCE_API)=>
void mod_print_print_name( const char *);
As you see, the function being declared (and defined at the end of the code) is not print_name, but rather mod_print_print_name. Go back to the initial code and see how the macro is intended to be used. I would assume that function calls are performed with the same macros that are used for declarations and definitions.

Resources