C compilation error : called object is not a function - c

I have created a macro for initializing a structure with some data, including a callback function pointer because this code is extensively reused in my file. I am storing the function pointer so I can simply iterate over the structure without having to explicitly check the msg_id and call the corresponding handling function.
These lines of code are around line number 150 :
typedef struct my_struct {
some_list *child_list;
void *data;
void *msg_func;
int nesting_level;
int msg_id;
} my_struct_t;
#define MALLOC_STRUCT_WITH_BASIC_DATA(level, msg_id, data_arg) \
my_struct_t *new_child = NULL; \
MY_CALLOC(new_child, my_struct_t, 1, failure); \
LISTCREATE(new_child->child_list); \
new_child->data = data_arg; \
#define INIT_MY_STRUCT(level, msg_id, data_arg, child_func) \
if (some_condition_on_data_arg_is_satisfied(data_arg)) { \
MALLOC_STRUCT_WITH_BASIC_DATA(level, msg_id); \
new_child->msg_func = &child_func; \
(new_child->msg_func)(new_child, new_child->data); \
}
There are about 100+ msg functions and the list will keep increasing in the future. Their declarations are around line 250 :
static void msg_function1(my_struct_t *st, data_type1 *ptr_data);
static void msg_function2(my_struct_t *st, data_type2 *ptr_data);
...
static void msg_functionn(my_struct_t *st, data_typen *ptr_data);
Finally, the macros are invoked around line number 580 and message handling functions are defined starting around line number 700.
I get a compilation error when the macro is encountered :
my_file.c:586: error: called object ‘new_child->msg_func’ is not a function
This is my first time using function pointers. I searched on stackoverflow and google and tried to eliminate possible causes, including ordering of function declaration and usage. Could someone please help me understand what am I doing wrong here? To note, I do not have permission to change the message handling functions' type to void * or something else.

You need to have a function pointer not an "ordinary" void pointer in your structure.
typedef struct my_struct {
some_list *child_list;
void *data;
void (*msg_func)(my_struct_t *, void *);
int nesting_level;
int msg_id;
} my_struct_t;
Ten message functions should convert the void pointer to the correct object pointer
static void msg_function2(my_struct_t *st, void *vData)
{
data_type2 *ptr_data = vData;
/* ... */

Related

Facing difficulty in using typedef on a function.....getting error "redeclared as different kind of symbol"

UART_ATMEGA328.h
#define UART_ATMEGA328_H_
void USART_Init(unsigned long); /* USART initialize function */
char USART_RxChar(); /* Data receiving function */
void USART_TxChar(char); /* Data transmitting function */
void USART_SendString(char*); /* Send string of USART data function */
#endif /* UART_ATMEGA328_H_ */
sim900.h
#define SIM900_H_
typedef void (*USART_Init)(unsigned long);
typedef void (*USART_SendString)(char*);
typedef void (*USART_TxChar)(char);
typedef struct
{
USART_Init start;
USART_SendString write;
USART_TxChar tx;
//Define anything else you need ..
}Sim900_Config_t;
void InitiateGSM(); //Check GSM
void SendSMS(char*); //Send SMS Function
void StoreSMS(); //Store SMS
#endif /* SIM900_H_ */
Error: 'USART_Init' redeclared as different kind of symbol/ 'USART_SendString' redeclared as different kind of symbol/ 'USART_TxChar' redeclared as different kind of symbol
You have a conflict between a function name and a type name. Nothing reasonable (ugly macros are not reasonable) can be done to resolve it.
I suggest selecting a new name for the types. Like adding _cb or _f suffix (abbreviated from "callback" or "function").
A minor tweak.
Consider making types for the functions, not the function pointers. It makes type declaration more digestible, especially when the function pointer is passed as a parameter or returned. Moreover, it does not hide the pointer in typedef.
typedef void config_init_f(unsigned long);
typedef void config_send_string_f(char*);
typedef void config_tx_char_f(char);
typedef struct
{
config_init_f* start;
config_send_string_f* write;
config_tx_char* tx;
//Define anything else you need ..
}Sim900_Config_t;

C Macros function definition syntax question

I've been looking through a program called hickit, and at one point (count.c, function starts at line 105), and they call a macros function (kavl_insert) from the Klib library as follows:
static void hk_count_nei2_core(int32_t n_pairs, struct cnt_nei2_aux *a, int r1, int r2)
{
struct cnt_nei2_aux *root = 0;
int32_t i, j, left;
unsigned cl;
left = 0;
kavl_insert(nei2, &root, &a[0], 0);
...
Looking at the Klib library (more specifically, in kavl.h), this function (I think) is defined as follows:
#define __KAVL_INSERT(suf, __scope, __type, __head, __cmp) \
__scope __type *kavl_insert_##suf(__type **root_, __type *x, unsigned *cnt_) { \
Later on in the kavl.h file there is this standalone line (line 322):
#define kavl_insert(suf, proot, x, cnt) kavl_insert_##suf(proot, x, cnt)
I don't have much technical knowledge with C (just learned parts as they were relevant), and I'm wondering how this works. The casing is different, and there is the "__" precursor in the #define line. How does this work?
The first __KAVL_INSERT macro is used to declare functions which all start with the same prefix (kavl_insert_) and end with the specified suffix (parameter suf).
So, when you see this:
__KAVL_INSERT(foo, static, int, null, null)
preprocessor will replace it with a function with the appropriate name, scope, and parameter types:
static int *kavl_insert_foo(int **root_, int *x, unsigned *cnt_) { \
/* actual function body ... */ \
/* with lots of trailing backshashes ... */ \
/* because it's the only way to create ... */ \
/* a multiline macro in C */ \
}
The lowercase kavl_insert macro, on the other hand:
kavl_insert(foo, &something, &whatever, 0);
simply expands to the actual function call, i.e. it's equivalent to calling the function defined above:
kavl_insert_foo(&something, &whatever, 0);
The idea behind this kind of macros is usually to create a generic type-safe data structure in C, using the preprocessor, like the klib library of various generic data structures.

C Macro for type safe callbacks

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.

Full macro in header file

I found a header to define hashtable with the following code :
#ifndef HASH_H
#define HASH_H
#define DEFINE_HASHTABLE(name, type, key, h_list, hashfunc)\
\
struct list * hashtable;\
\
static int hashtable_init (size_t size)\
{\
unsigned long i;\
hashtable = (struct list*)malloc(size * sizeof (struct list_head));\
if (!hashtable)\
return -1;\
for (i = 0; i < size; i++)\
INIT_LIST_HEAD(&hashtable[i]);\
return 0;\
}\
\
static inline void hashtable_add(type *elem)\
{\
struct list_head *head = hashtable + hashfunc(elem->key);\
list_add(&elem->h_list, head);\
}\
\
static inline void hashtable_del(type *elem)\
{\
list_del(&elem->h_list);\
}\
\
static inline type * hashtable_find(unsigned long key)\
{\
type *elem;\
struct list_head *head = hashtable + hashfunc(key);\
\
list_for_each_entry(elem, head, h_list){\
if (elem->key == key) \
return elem; \
}\
return NULL;\
}
#endif /* _HASH_H */
I never seen a header file such this one. What is the advantage of this way to write a header (I mean full macro)? Is it about genericity or things like that?
It's a way to try to ensure that all the hash function calls have their inline request granted, i.e. to reduce the number of function calls when doing hash table operations.
It's just an attempt, it can't guarantee that the functions will be inlined, but by making them static the chance at least improves. See this question for lots of discussion about this, in particular #Christoph's answer here.
Note that it will only work once per C file, since there's no "unique" part added to the function names.
If you do:
#include "hash.h"
DEFINE_HASHTABLE(foo, /* rest of arguments */);
DEFINE_HASHTABLE(bar, /* another bunch of args */);
you will get compilation errors, since all the hashtable_ functions will be defined twice. The macro writer could improve this by adding the name to all the things defined (variables and functions) by the set of macros.
I.e. this:
struct list * hashtable;\
\
static int hashtable_init (size_t size)\
should become something like:
static list *hashtable_ ##name;\
\
static int hashtable_ ##name ##_init(size_t size)\
and so on (where name is the first macro argument, i.e. the foo and bar from my example usage above).

Rewrite GCC cleanup macro with nested function for Clang?

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

Resources