Struct initialisation through macro overuse - c

I've got some structs to initialise, which would be tedious to do manually. I'd like to create a macro that will help me with it... but I'm not sure the C preprocessor is good enough for this.
I've got structs which represent menus. They consist of function pointers only:
typedef uint8_t (*button_handler) (uint8_t);
typedef void (*pedal_handler) (void);
typedef void (*display_handler) (void);
typedef void (*menu_switch_handler) (void);
#define ON_BUTTON(x) uint8_t menu_frame_##x##_button (uint8_t button)
#define ON_PEDAL(x) void menu_frame_##x##_pedal (void)
#define ON_DISPLAY(x) void menu_frame_##x##_display (void)
#define ON_SWITCH(x) void menu_frame_##x##_switch (void)
typedef struct menu_frame {
button_handler on_button;
pedal_handler on_pedal;
display_handler on_display;
menu_switch_handler on_switch;
} menu_frame;
That allows me to write the functions and separate functions as (.c file):
ON_BUTTON(blah) { ... }
and menus as (.h file):
ON_BUTTON(blah);
ON_DISPLAY(blah);
menu_frame menu_frame_blah = {
menu_frame_blah_button,
NULL,
menu_frame_blah_display,
NULL
};
Is there any way I can fold the menu definition into one define? I could do something that expands MENU(blah, menu_frame_blah_button, NULL, menu_frame_blah_display, NULL) of course, but is there any way to:
make it shorter (NULL or some name)
remove the need of ON_BUTTON(...); from before the struct
Ideally, I'd like MENU(blah, button, NULL, display, NULL) to both define the handlers and the menu struct itself. I don't know for example how to prevent expanding the last term into ON_SWITCH(NULL).
Or maybe I should approach it from some other way?

I've written Python scripts to generate this sort of code for me before. You may want to go that route and just work the script into your build process.

You cannot do conditional macro expansion in C, so that your macro would be expanded differently depending on the arguments, as in: you cannot use #if within macro definition.
I guess the best you could get would be something like MENU(blah, ITEM(blah,button), NULL, ITEM(blah,display), NULL), and you still need a separate set for prototypes because of lack of conditional expansion.
Personally, I would write a simple script to generate that sort of boilerplate C code. One that would understand your desired syntax. In Python or whatever suits you best…

You can program conditionals, finite loops, default arguments and all such stuff in the preprocessor alone. The Boost library has an implementation of some of that in their preprocessor section. Boost is primarily for C++, but the preprocessor stuff should basically work in C as well.
By such techniques you can write complicated macros but that are simple to use. It gets a bit simpler to implement when using C99 instead of C89 (you have named initializers and VA_ARGS), but still.

Related

How to not repeat myself in this situation? C functions that are the same but have different arguments

Now I know what you are thinking - the thing that I described in the title sounds just like overloading. I know that is not a thing in C and I'm not going for it anyways. I have these 2 functions - ABSOLUTELY the same in their body, but the arguments are 2 different structs. Basically it's a binary search tree struct and a red black tree struct. As you may know the structs have only one difference - the red black tree struct contains one more field and that's the color one. Also the functions search, min, max, predecessor, successor.. those are going to have the EXACT same body but alas they take 2 different types of structs. And of course the insert and delete methods will be different.
So I was thinking how can I avoid breaking the number one rule in programming and not repeat myself? I thought about a lot of solutions but none work when I try to find a way to implement it. I thought about just using one function for both but I can't do that since the structs are different. I thought about using macros but honestly I have no idea how to make those work and I am not even sure that they can avoid the problem that I have 2 different structs. I thought about making one generic struct and have the rb struct contain it and a color variable but this straight up changes the code with a few characters everywhere since I have to go one level deeper into the struct to get the values and I no longer have duplicate code.
Just an example of what the problem looks like:
bst_search(bstTree t, char *k)
{
// Searching in tree
}
rb_search(rbTree t, char *k)
{
// SAME code for searching in tree
}
If I was coding in java I would probably solve this using an abstract superclass but C doesn't have fancy stuff like that.
Some extra info: both implementations have their own header and class files and I'd like to keep it that way. Right now I have duplicate code all over those 2 classes and the only things differing are the names of the functions and the structs (except for the insert and delete functions ofc).
Sorry if this has an obvious solution I just don't find a way out of this without duplicating my code.
If you create the rbTree with a bstTree as the first member thus:
typedef struct
{
bstTree common ;
int color ;
} rbTree
Then you can safely cast an rbTree to a bstTree, so rb_search() can be implemented as a simple macro thus:
#define rb_search(t, k) bst_search( (bstTree*)(t). k )
One problem is that now for any code that is unique to rbTree you have to access most of the members via teh common member. That however is not entirely necessary; if you do not define rbTree with a bstTree member, but simply ensure that both are defined identically with the common members first and in the same order and type, you will be able to cast one to the other and access the members so long as the same packing and alignment options are applied to all modules that use the structures - doing that however is far less safe and less easily maintained. A somewhat ugly but safer way to do this is to place the common members in an include file and #include the members in each struct definition.
There is no good way of doing it in C (in contrast to C++ where templates exist for exactly this purpose).
Ugly way #1. By using macro:
#define MAKE_SEARCH_FUNCTION(FN_NAME, VAR_TYPE) \
FN_NAME(VAR_TYPE t, char *k) \
{ \
/* Searching in tree */ \
}
struct bstTree {
};
MAKE_SEARCH_FUNCTION(bst_search, struct bstTree*)
struct rbTree {
};
MAKE_SEARCH_FUNCTION(rb_search, struct rbTree*)
Ugly way #2. By moving body into separate include file. A bit more work, but makes sense if function is very large or if you need to generate whole families of functions at once (e.g. bst_search()/bst_add()/ bst_remove()).
// header.h
FN_NAME(VAR_TYPE t, char *k)
{
// Searching in tree
}
// source.c
struct bstTree {
};
#define VAR_TYPE struct bstTree*
#define FN_NAME bst_search
#include "header.h"
#undef VAR_TYPE
#undef FN_NAME
struct rbTree {
};
#define VAR_TYPE struct rbTree*
#define FN_NAME rb_search
#include "header.h"
#undef VAR_TYPE
#undef FN_NAME
A macro that acted on a generic input tree would make it, but I find that solution somehow dirty.
Another approach is to have a generic struct with all the members of both trees together, without nested structs. For example:
struct genericTree {
// common members for both trees
...
// members for rb trees
...
// members for bst
...
}
Then you have a single function:
search(genericTree* t, char* k)
To keep the semantics, use typedefs:
typedef genericTree bstTree;
typedef genericTree rbTree;
So you can still have functions that get a bstTree or a rbTree when they expect only one if those types.
The drawback of this approach is that you take more memory for a single tree because you keep members of the other. You may ease it with some unions, probably.

Declaring data type of a variable using a condition in c

I want to declare data type of a variable depending on a condition in C. Is it possible?
I have written a program to implement stack using integer array,
and I want the same code to implement stack of characters which is nothing but replacing some "int"s by "char"s, So how to do that??
I trid something like,
if(x == 1)
#define DATATYPE int
else
#define DATATYPE char
and many other things too but nothing worked.
Your code could work with #if x==1 ... #endif if x is a preprocessor symbol, e.g. if you compile with -Dx=1 command-line option to gcc ; please understand that the C preprocessor is the first phase of a C compiler, which in fact sees preprocessed code (use e.g. gcc -C -E source.c > source.i to get into source.i the preprocessed form of source.c)
In general, you could implement such generic containers using huge preprocessor macros. See e.g. sglib and this question. Or you could generate your C code with some specialized source code generator (perhaps using another preprocessor like m4 or gpp, or crafting your own generator in some scripting language).
Alternatively, use a lot of void* pointers, and pass the size of data to your routines, like qsort(3) does. See e.g. Glib containers
You might be interested in learning C++11 or Ocaml (or even Common Lisp). They offer a standard library with several generic containers (in C++ with templates in the library, in Ocaml with functors in it); read also about generic programming
You probably have a design flaw. You should really ask yourself why you want to threat C as a dynamic language like Python. C is a statically language typed, so types are fixed.
Use this solution which encourage you to redesign by creating a struct for each value in the stack tagged_t,and then fill the data, I hope you get the idea.
typedef union {
int i;
char c;
float f;
} evil;
typedef struct {
evil value;
int type;
} tagged_t;
enum {
TYPE_INT, TYPE_CHAR, TYPE_FLOAT
};
tagged_t bar;
bar.value.c = 'a';
bar.type = TYPE_CHAR;
See the answer of Yann Ramin
Firstly, please learn about the pre-processor. Now, on to your question.
This does not work, due to the fact that the compiler only actually sees:
if(x == 1)
else
The # indicates that the instruction will be executed by the pre-processor. The pre-processor is really a glorified find-and-replace when we talk about the #define command. eg:
#define PI_5_DIGITS 3.14159f
The pre-processor will find all occurrences of the tag PI_5_DIGITS and replace it with 3.14159.
Should you want to use this, make x a pre-processor symbol, by adding the switch e.g. -Dx=1.
Your code would then need to be changed to:
#ifdef x
#define DATATYPE int
#else
#define DATATYPE char
#endif
Suggested reading:
http://www.phanderson.com/C/preprocess.html
http://gcc.gnu.org/onlinedocs/cpp

if defined in C struct

Can if defined (XX) be placed inside a struct/union in a header file?
struct
{
int i;
#if defined(xx)
int j;
#endif
}t;
I am dealing with a large file base of .c and .h files and I need to know the possible cons of this type of usage.
While completely valid, a definite con to using this is any time you need to use t.j you would also have to surround it with your #if defined(xx) otherwise you will invoke compiler errors
Sure you can. The preprocessor can be used for anything, no need to feed it C. The cons of this useage are, that you have a struct which changes size depending on wether xx is defined or not. This is asking for trouble, because a library built with this define and somebody using this library without the define are having different structs....
Preprocessor directives such as #if can be placed anywhere in your program. They have no actual relationship to the C code (or anything else) that is present in the text (except comments), since they are processed before the compilation phase. You can do stupid things like the code below, although it is generally a bad idea.
int foo(int x)
{
#if defined MONKEY
return 0;
}
int bar(int x)
{
#endif
return x;
}

Elegant way to emulate 'this' pointer when doing OOP in C?

I want to do some object-oriented style programming in C using polymorphism, where my interface class contains a pointer to a table of functions. Example something like:
/* Implement polymorphism in C, Linux kernel-style */
struct statement {
const struct statement_ops *ops;
struct list_head list; /* when on master input list */
void *private; /* pointer to type-specific data */
};
struct statement_ops {
int (*analyse)(void *private, int pc);
int (*get_binary_size)(void *private);
};
void user(void)
{
struct statement *s = make_a_statement();
if (s->ops->analyse(s->private, foo))
blah blah;
}
I'd like to be able to write something without explicitly passing s->private into every "method". Any ideas? Some macro tricks maybe?
If this is part of the public interface, you can add accessor functions. A hidden benefit is that you can do sanity checks and other work in the accessor. (Note I called the "this" pointer "o", as in "object". I prefer it that way for consistency.)
int statement_analyse (struct statement *o, int pc)
{
assert(pc >= 0);
int ret = o->ops->analyse(o->private, pc);
assert(ret >= 0);
return ret;
}
You can now call this without the explicit passing of "private".
void user(void)
{
struct statement *s = make_a_statement();
if (statement_analyse(s, foo))
blah blah;
}
While it may seem that this provides no benefit, because you still have to implement the accessors, assuming that you want a well defined and robust interface, the accessor functions are the only sane place to put the assertions and the interface documentation. In fact, if you write good assertions, the assertions themselves help document the interface. And once you add sanity checks in the accessors, you don't have to add them in the actual methods they call.
Of course, this approach only makes sense when the function called via the function pointer will be something provided by the user, or in some other way can be different things. If there's a single analyse() method that will always do the same thing, you can simply implement a statement_analyse() that directly does what it needs to do.
Small note: when doing OOP, I prefer to typedef the structs and give them CamelCase names. I use this convention as a way of telling that the struct is opaque and should only be accessed via its public interface. It also looks nicer, though that is subjective. I also prefer having the user allocate the memory for the struct itself, as opposed to the constructor malloc'ing it. That avoids having to handle malloc failure, and makes the program a little bit more efficient.
typedef struct {
...
} Statement;
void Statement_Init (Statement *o);
int Statement_Analyse (Statement *o, int pc);
Unfortunately, writing your methods to allow the passing of a self or this object is the only way to achieve this in C.
You can use macro tricks to hide part of it, but at that point it's not really C any more.
As the other answers say, there is no way to do this without calling the function with the appropriate pointer, but (as Williham Totland suggests) you could use macros to streamline the calls (requires a compiler with variadic macro support):
// macro_call.c
#define C_ARGS(stmnt, func, ...) (stmnt)->ops->func((stmnt)->private, ...)
#define C_NOARGS(stmnt, func) (stmnt)->ops->func((stmnt)->private)
C_ARGS(s, analyse, 1);
C_ARGS(s, lots_of_args, 1, 2, 3, 4);
C_NOARGS(s, no_args);
(The C is for "call".)
Doing the preprocessing on that (via gcc -E macro_call.c) gives:
(s)->ops->analyse((s)->private, 1);
(s)->ops->lots_of_args((s)->private, 1, 2, 3, 4);
(s)->ops->no_args((s)->private);
This is similar to the accessor function version: the macro version is slightly more flexible in some ways, but it is also less safe and could lead to subtle errors and mistakes.
There are two macros because passing no extra arguments to C_ARGS would result in s->ops->func(s->private, ), I think it is possible to fix this, but it is awkward and would require significantly more code (empty __VA_ARGS__ are notoriously hard to deal with).

#undef-ing in Practice?

I'm wondering about the practical use of #undef in C. I'm working through K&R, and am up to the preprocessor. Most of this was material I (more or less) understood, but something on page 90 (second edition) stuck out at me:
Names may be undefined with #undef,
usually to ensure that a routine is
really a function, not a macro:
#undef getchar
int getchar(void) { ... }
Is this a common practice to defend against someone #define-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting getchar(), so it shouldn't come up.) With your own function names, do you feel the need to do this? Does that change if you're developing a library for others to use?
What it does
If you read Plauger's The Standard C Library (1992), you will see that the <stdio.h> header is allowed to provide getchar() and getc() as function-like macros (with special permission for getc() to evaluate its file pointer argument more than once!). However, even if it provides macros, the implementation is also obliged to provid actual functions that do the same job, primarily so that you can access a function pointer called getchar() or getc() and pass that to other functions.
That is, by doing:
#include <stdio.h>
#undef getchar
extern int some_function(int (*)(void));
int core_function(void)
{
int c = some_function(getchar);
return(c);
}
As written, the core_function() is pretty meaningless, but it illustrates the point. You can do the same thing with the isxxxx() macros in <ctype.h> too, for example.
Normally, you don't want to do that - you don't normally want to remove the macro definition. But, when you need the real function, you can get hold of it. People who provide libraries can emulate the functionality of the standard C library to good effect.
Seldom needed
Also note that one of the reasons you seldom need to use the explicit #undef is because you can invoke the function instead of the macro by writing:
int c = (getchar)();
Because the token after getchar is not an (, it is not an invocation of the function-like macro, so it must be a reference to the function. Similarly, the first example above, would compile and run correctly even without the #undef.
If you implement your own function with a macro override, you can use this to good effect, though it might be slightly confusing unless explained.
/* function.h */
…
extern int function(int c);
extern int other_function(int c, FILE *fp);
#define function(c) other_function(c, stdout);
…
/* function.c */
…
/* Provide function despite macro override */
int (function)(int c)
{
return function(c, stdout);
}
The function definition line doesn't invoke the macro because the token after function is not (. The return line does invoke the macro.
Macros are often used to generate bulk of code. It's often a pretty localized usage and it's safe to #undef any helper macros at the end of the particular header in order to avoid name clashes so only the actual generated code gets imported elsewhere and the macros used to generate the code don't.
/Edit: As an example, I've used this to generate structs for me. The following is an excerpt from an actual project:
#define MYLIB_MAKE_PC_PROVIDER(name) \
struct PcApi##name { \
many members …
};
MYLIB_MAKE_PC_PROVIDER(SA)
MYLIB_MAKE_PC_PROVIDER(SSA)
MYLIB_MAKE_PC_PROVIDER(AF)
#undef MYLIB_MAKE_PC_PROVIDER
Because preprocessor #defines are all in one global namespace, it's easy for namespace conflicts to result, especially when using third-party libraries. For example, if you wanted to create a function named OpenFile, it might not compile correctly, because the header file <windows.h> defines the token OpenFile to map to either OpenFileA or OpenFileW (depending on if UNICODE is defined or not). The correct solution is to #undef OpenFile before defining your function.
Although I think Jonathan Leffler gave you the right answer. Here is a very rare case, where I use an #undef. Normally a macro should be reusable inside many functions; that's why you define it at the top of a file or in a header file. But sometimes you have some repetitive code inside a function that can be shortened with a macro.
int foo(int x, int y)
{
#define OUT_OF_RANGE(v, vlower, vupper) \
if (v < vlower) {v = vlower; goto EXIT;} \
else if (v > vupper) {v = vupper; goto EXIT;}
/* do some calcs */
x += (x + y)/2;
OUT_OF_RANGE(x, 0, 100);
y += (x - y)/2;
OUT_OF_RANGE(y, -10, 50);
/* do some more calcs and range checks*/
...
EXIT:
/* undefine OUT_OF_RANGE, because we don't need it anymore */
#undef OUT_OF_RANGE
...
return x;
}
To show the reader that this macro is only useful inside of the function, it is undefined at the end. I don't want to encourage anyone to use such hackish macros. But if you have to, #undef them at the end.
I only use it when a macro in an #included file is interfering with one of my functions (e.g., it has the same name). Then I #undef the macro so I can use my own function.
Is this a common practice to defend against someone #define-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting getchar(), so it shouldn't come up.)
A little of both. Good code will not require use of #undef, but there's lots of bad code out there you have to work with. #undef can prove invaluable when somebody pulls a trick like #define bool int.
In addition to fixing problems with macros polluting the global namespace, another use of #undef is the situation where a macro might be required to have a different behavior in different places. This is not a realy common scenario, but a couple that come to mind are:
the assert macro can have it's definition changed in the middle of a compilation unit for the case where you might want to perform debugging on some portion of your code but not others. In addition to assert itself needing to be #undef'ed to do this, the NDEBUG macro needs to be redefined to reconfigure the desired behavior of assert
I've seen a technique used to ensure that globals are defined exactly once by using a macro to declare the variables as extern, but the macro would be redefined to nothing for the single case where the header/declarations are used to define the variables.
Something like (I'm not saying this is necessarily a good technique, just one I've seen in the wild):
/* globals.h */
/* ------------------------------------------------------ */
#undef GLOBAL
#ifdef DEFINE_GLOBALS
#define GLOBAL
#else
#define GLOBAL extern
#endif
GLOBAL int g_x;
GLOBAL char* g_name;
/* ------------------------------------------------------ */
/* globals.c */
/* ------------------------------------------------------ */
#include "some_master_header_that_happens_to_include_globals.h"
/* define the globals here (and only here) using globals.h */
#define DEFINE_GLOBALS
#include "globals.h"
/* ------------------------------------------------------ */
If a macro can be def'ed, there must be a facility to undef.
a memory tracker I use defines its own new/delete macros to track file/line information. this macro breaks the SC++L.
#pragma push_macro( "new" )
#undef new
#include <vector>
#pragma pop_macro( "new" )
Regarding your more specific question: namespaces are often emul;ated in C by prefixing library functions with an identifier.
Blindly undefing macros is going to add confusion, reduce maintainability, and may break things that rely on the original behavior. If you were forced, at least use push/pop to preserve the original behavior everywhere else.

Resources