using #defines and passing functions to them - c

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.

Related

Print name of caller function

I found __FUNCTION__ macro that will give the name of currently executing function, But is there any macro available to print the name of parent function (a function that invoked currently running function) ?
void print_error_message(const char *msg)
{
printf("%s : %s\n",__FUNCTION__,msg);
}
int main()
{
print_error_message("failed to connect");
return 0;
}
The above program will give output :
print_error_message : failed to connect
But what I actually required is
main : failed to connect
because main() invoked print_error_message()
I don't want to pass one more argument to function print_error_message() like print_error_message(__FUNCTION__, msg), what I am expecting is a similar macro or function to retrieve the name of the caller function.
There's no standard way to get the name from the call-stack, and if debug information is stripped or otherwise unavailable there's possible no way at all to get the name.
As a simple workround, you could use macros:
#define print_error_message(msg) actual_print_error_message(__FUNCTION__, (msg))
void actual_print_error_message(const char *func, const char *msg)
{
printf("%s : %s\n",func,msg);
}
Note that __FUNCTION__ is not standard C, it's an extension. For standards-compliance use the C99 special predefined variable __func__.
You could let the caller pass its function name as a parameter. For example:
void print_error_message(const char *msg, const char *caller)
{
printf("%s : %s\n",caller,msg);
}
int main()
{
print_error_message("failed to connect", __FUNCTION__);
return 0;
}
No, it is not available and it is not possible.
Because value of a macro like __FUNCTION__ is calculated in preprocessing phase and what you want to do is not possible in that phase.
I don't want to pass one more argument to function [...] I am expecting is a similar macro or function to retrieve the name of the caller function.
This does not exist, at least not as part of the C standard.
On Linux GCC provides the capability to pull backtrace info. Perhaps this helps you.

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

Is function pointer type in _Generic assoc-list not working as expected?

I was experimenting with "hacking" the type-system, by not restricting the function pointer argument to accept a function with a specific type of arguments. However, I still wanted to make it type-safe, so I thought I will combine this "hack" with the possibilities of the _Generic keyword.
I have the following four functions:
#include <stdio.h> /* printf() */
#include <stdlib.h> /* EXIT_SUCCESS */
static void
function_i(int *i)
{
printf("%d\n", *i);
}
static void
function_f(float *f)
{
printf("%.2ff\n", *f);
}
static void
caller(void(*func)(),
void *arg)
{
func(arg);
}
static void
except(void(*func)(),
void *arg)
{
printf("unsupported type\n");
}
The first and second will be passed to the third, and I want to make sure, if the type of the function and the argument passed to the third is not right, then the fourth function will be called. Therefore I created the following _Generic selector:
#define handler(func, arg) _Generic((func), \
void(*)(int*): _Generic((arg), \
int* : caller, \
default : except), \
void(*)(float*): _Generic((arg), \
float* : caller, \
default : except), \
default: except)(func, arg)
And then I called them:
int main(void)
{
int i = 12;
float f = 3.14f;
void(*func_ptr_i)(int*) = function_i;
void(*func_ptr_f)(float*) = function_f;
handler(function_i, &i);
handler(function_f, &f);
handler(func_ptr_i, &i);
handler(func_ptr_f, &f);
return EXIT_SUCCESS;
}
The output is very interesting:
unsupported type
unsupported type
12
3.14f
I expected this to work for the first two cases as well, without the need to create a specific function pointer variable for the passed functions. The question is: is this an implementation error in clang's _Generic, or this is the expected behavior? Is so, I'm very curious about why exactly? And how to make it work without creating extra function pointers?
Thanks in advance!
SYS-INFO:
compiler: Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
flags: cc -std=c11 -Wall -v -g
The problem that you are facing is that the choice expression of _Generic is not evaluated. If it would be, your function names would decay to function pointers and everything would work.
Adding a & to your choice expression should fix that.

How to pass parameters in c from library linux

How to pass parameters from library in c programming language in linux?
I've tried this:
library.c code:
char test;
void GetParam()
{
test = "Creating test string here.";
}
header.h code
extern char test;
void GetParam(void);
program.c code
int main()
{
GetParam();
printf("%s\n", test);
}
but test returns empty.
char test just stores one character. If you want it to store a string, use char *test
PS: I'm a beginner; please correct me if I am wrong.

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

Resources