I am currently working on a project in C in which there are various function that all need become encapsulated in between two other functions. Schematically, it looks like this:
int func1(int arg) {
prepare();
doStuff();
undo();
return stuff;
}
char func2(int arg1, char* arg2) {
prepare();
doOtherStuff();
undo();
return results;
}
I've heard the preprocessor is quite powerful, so is it possible to insert the prepare() and undo() functions before and after the actual function body using some preprocessor mumbo-jumbo? I know that it is highly advised not to use the preprocessor if it can be avoided, yet I still am curious whether it is possible.
Cheers.
Just for the record, an alternative would be to set up some form of function pointer template system:
typedef void stuff_t (void*);
void execute (stuff_t* stuff, void* result)
{
prepare();
stuff(result);
undo();
}
int func1(int arg) {
int result;
execute(do_stuff, &result);
return result;
}
char func2(int arg1, char* arg2) {
char result;
execute(doOtherStuff, &result);
return result;
}
Whether this is a good idea or not depends on what the code is actually supposed to do and what requirements there are on code re-usability.
There you go:
#define MY_MACRO(doStuff) \
{ \
prepare(); \
doStuff \
undo(); \
}
Related
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.
I'm trying to create a very simple event system in c. My interface looks like this:
typedef struct EventEmitter EventEmitter;
EventEmitter* emitter_create();
void emitter_subscribe(EventEmitter* emitter, void (*cb)(void*));
void emitter_publish(EventEmitter* emitter, void *payload);
Everything works correctly, but in order to register an event listener, I need to provide a function pointer that takes a void *.
static void registerOnKeyDown(void (*cb)(void*)) {
emitter_subscribe(keyDownEmitter, cb);
}
static void registerOnKeyUp(void (*cb)(void*)) {
emitter_subscribe(keyUpEmitter, cb);
}
Is there any way, using a macro or otherwise, to allow users of EventEmitters to provide a typed callback? Something like:
void onKey(int keyCode) {
printf("%d", keyCode);
}
instead of:
void onKey(void *keyCode) {
int code = (int)keyCode;
printf("%d", code);
}
I ended up solving this by simply casting to and from void (*cb)(void *) as needed in wrapper functions:
typedef void (*keyCallback)(int);
typedef void (*emitterCallback)(void*);
static void registerOnKeyDown(keyCallback cb) {
emitter_subscribe(keyDownEmitter, (emitterCallback)cb);
}
If you know what your types are, you can use C11 generic selection to find out the type of the argument, and provide it as an enum value.
#include <stdio.h>
typedef struct EventEmitter EventEmitter;
typedef void (*INT_CALLBACK)(int);
typedef void (*VOIDP_CALLBACK)(void *);
enum cbtype {
_INT_CB,
_VOIDP_CB
};
void _safe_emitter_subscribe(EventEmitter *emitter,
void (*callback)(),
enum cbtype type)
{
printf("Registering a callback of type %d\n", type);
}
#define safe_emitter_subscribe(emitter, callback) \
_safe_emitter_subscribe( \
emitter, \
(void (*)())callback, \
_Generic(callback, \
INT_CALLBACK: _INT_CB, \
VOIDP_CALLBACK: _VOIDP_CB))
void func1(int a) {
}
void func2(void *a) {
}
int main(void) {
safe_emitter_subscribe(NULL, func1);
safe_emitter_subscribe(NULL, func2);
}
Then from the enum value you will know how you'd need to cast the function again: If it is _INT_CB it must be recast as INT_CALLBACK before calling; _VOIDP_CB as VOIDP_CALLBACK and so on.
See this answer on Software Engineering SE.
Given your API:
typedef struct EventEmitter EventEmitter;
EventEmitter* emitter_create();
void emitter_subscribe(EventEmitter* emitter, void (*cb)(void*));
void emitter_publish(EventEmitter* emitter, void *payload);
if you modify it to define the subscription macro on that API instead of putting off on the client code, like this:
typedef struct EventEmitter EventEmitter;
EventEmitter* emitter_create();
void emitter_subscribe_impl(EventEmitter* emitter, void (*cb)(void*));
#define emitter_subscribe(emitter, xFunc) emitter_subscribe_impl((emitter), (void(*)(void*))(xFunc))
void emitter_publish_impl(EventEmitter* emitter, void *payload);
#define emitter_publish(emitter, xFunc) emitter_publish_impl((emitter), (void(*)(void*)(xFunc))
Then subscribers can call it with the type that they have in hand. As with all API macros, make sure you document the expected arguements completely, so consumers know what to provide and what to expect.
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);
}
I'm trying to work through an issue on a third party library. The issue is the library uses GCC's nested functions buried in a macro, and Clang does not support nested functions and has no plans to do so (cf., Clang Bug 6378 - error: illegal storage class on function).
Here's the macro that's the pain point for me and Clang:
#define RAII_VAR(vartype, varname, initval, dtor) \
/* Prototype needed due to http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36774 */ \
auto void _dtor_ ## varname (vartype * v); \
void _dtor_ ## varname (vartype * v) { dtor(*v); } \
vartype varname __attribute__((cleanup(_dtor_ ## varname))) = (initval)
And here's how its used (from the code comments):
* void do_stuff(const char *name)
* {
* RAII_VAR(struct mything *, thing, find_mything(name), ao2_cleanup);
* if (!thing) {
* return;
* }
* if (error) {
* return;
* }
* do_stuff_with_thing(thing);
* }
The Clang User Manual states to use C++ and a lambda function to emulate. I'm not sure that's the best strategy, and a C project will likely not accept a C++ patch (they would probably tar and feather me first).
Is there a way to rewrite the macro so that's its (1) more accommodating to Clang, and (2) preserves original function semantics?
Clang doesn't support GCC nested functions, but it does support Objective C-style "blocks", even in C mode:
void f(void * d) {
void (^g)(void *) = ^(void * d){ };
g(d);
}
You need to invoke it with the clang command rather than gcc, and also (?) pass -fblocks -lBlocksRuntime to the compiler.
You can't use a block as a cleanup value directly, since it has to be a function name, so (stealing ideas from here) you need to add a layer of indirection. Define a single function to clean up void blocks, and make your RAII'd variable the block that you want to run at the end of the scope:
typedef void (^cleanup_block)(void);
static inline void do_cleanup(cleanup_block * b) { (*b)(); }
void do_stuff(const char *name) {
cleanup_block __attribute__((cleanup(do_cleanup))) __b = ^{ };
}
Because blocks form closures, you can then place the operations on your variables to cleanup directly inside that block...
void do_stuff(const char *name) {
struct mything * thing;
cleanup_block __attribute__((cleanup(do_cleanup))) __b = ^{ ao2_cleanup(thing); };
}
...and that should run at the end of the scope as before, being invoked by the cleanup on the block. Rearrange the macro and add a __LINE__ so it works with multiple declarations:
#define CAT(A, B) CAT_(A, B)
#define CAT_(A, B) A##B
#define RAII_VAR(vartype, varname, initval, dtor) \
vartype varname = (initval); \
cleanup_block __attribute__((cleanup(do_cleanup))) CAT(__b_, __LINE__) = ^{ dtor(varname); };
void do_stuff(const char *name) {
RAII_VAR(struct mything *, thing, NULL, ao2_cleanup);
...
Something like that, anyway.
I believe you can do this without using a clang-specific version, I'd try something like this (untested, may require a few extra casts):
struct __destructor_data {
void (*func)(void *);
void **data;
}
static inline __destructor(struct __destructor_data *data)
{
data->func(*data->data);
}
#define RAII_VAR(vartype, varname, initval, dtor) \
vartype varname = initval; \
__attribute((cleanup(__destructor))) \
struct __destructor_data __dd ## varname = \
{ dtor, &varname };
In our project we have a gcc-specific _auto_(dtor) macro that precedes the normal variable declaration, e.g.:
_auto_(free) char *str = strdup("hello");
In this case our macro can't add anything after the variable declaration and also doesn't know the name of the variable, so to avoid using gcc-specific nested functions I came up with the following hackish version in case this helps anyone:
static void *__autodestruct_value = NULL;
static void (*__autodestruct_dtor)(void *) = NULL;
static inline void __autodestruct_save_dtor(void **dtor)
{
__autodestruct_dtor = *dtor;
__autodestruct_dtor(__autodestruct_value);
}
static inline void __autodestruct_save_value(void *data)
{
__autodestruct_value = *(void **) data;
}
#define __AUTODESTRUCT(var, func) \
__attribute((cleanup(__autodestruct_save_dtor))) \
void *__dtor ## var = (void (*)(void *))(func); \
__attribute((cleanup(__autodestruct_save_value)))
#define _AUTODESTRUCT(var, func) \
__AUTODESTRUCT(var, func)
#define _auto_(func) \
_AUTODESTRUCT(__COUNTER__, func)
This is hackish because it depends on the order the destructors are called by the compiler being the reverse of the order of the declarations, and it has a few obvious downsides compared to the gcc-specific version but it works with both compilers.
Building on the answers above, here's my hack to allow clang to compile nested procedures written in gcc-extension style. I needed this myself to support a source-to-source translator for an Algol-like language (Imp) which makes heavy use of nested procedures.
#if defined(__clang__)
#define _np(name, args) (^name)args = ^args
#define auto
#elif defined(__GNUC__)
#define _np(name, args) name args
#else
#error Nested functions not supported
#endif
int divide(int a, int b) {
#define replace(args...) _np(replace, (args))
auto int replace(int x, int y, int z) {
#undef replace
if (x == y) return z; else return x;
};
return a / replace(b,0,1);
}
int main(int argc, char **argv) {
int a = 6, b = 0;
fprintf(stderr, "a / b = %d\n", divide(a, b));
return 0;
}
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;
}