typedef struct
{
struct item_t items[MAX_ITEMS];
int num_items;
} item_list_t;`
items_list_t item_list =
{
.items =
{
#ifdef ITEM1
{
/* item1 initialized here */
},
#endif
#ifdef ITEM2
{
/* item2 initialized here */
},
#endif
#ifdef ITEM3
{
/* item3 initialized here */
},
#endif
}
/* Find out how many items were initialized */
.num_items = sizeof(items) / sizeof(struct item_t); //doesn't work
}
I am trying to find a way to populate the .num_items field with the number of items in the array that were initialized at compile time. I know why the code example doesn't work, im wondering if there is there any way of accomplishing this?
A not portable hack would be to use the __COUNTER__ preprocessor extension. It's not a standard C feature, but should be supported in recent gcc, clang and msvc compilers.
The preprocessor increments the value of the counter after each evaluation, so you have to force evaluation using something like:
// in case __COUNTER__ was previously used in a different header
const static int initial_counter = __COUNTER__;
#ifdef ITEM1
const static int item1_defined = __COUNTER__; // +1
#endif
#ifdef ITEM2
const static int item2_defined = __COUNTER__; // +1
#endif
#ifdef ITEM3
const static int item3_defined = __COUNTER__; // +1
#endif
// must subtract 1 because this line also evaluates __COUNTER__
const static int total_item_count = (__COUNTER__) - initial_counter - 1;
And then:
items_list_t item_list =
{
.items = { ... },
.num_items = total_item_count
}
A more portable preprocessor alternative is to use Boost which should be more portable (but it's written for C++ so you might have to port some of the details to C yourself), or use a code generator (recommended).
Involving a code generator into your build scripts will generate actual source code you can step in and debug if needed. Preprocessor hacks can easily get out of hand.
Related
There are many functions in the C libraries that require users to input with macros.
I wonder, if I have an array of strings, with contents of macros, like so:
char s[][3] = {"SIGINT", "SIGKILL", "SIGSTOP"};
How can I pass these strings as macros? (Like so:)
signal(s[0], do_something);
with do_something is a function pointer.
(and yes, technically I can pass ints in this case, but... hypothetically, ya know?)
EDIT:
As #RemyLebeau and SGeorgiades point out, the "SIGINT",... are aliases for integer consts, and therefore can be stored in an int array, like so:
int s[3] = {SIGINT, SIGKILL, SIGSTOP};
Although SGeorgiades and Remy Lebeau already gave you the answer, here is something that I've used in the past to allow conversion and pretty printing of signal numbers and names:
#include <stdio.h>
#include <signal.h>
#include <string.h>
struct sigfun {
int signo;
const char *signame;
};
#define SIGFUN(_sig) \
{ \
.signo = _sig, \
.signame = #_sig \
}
struct sigfun siglist[] = {
SIGFUN(SIGINT),
SIGFUN(SIGKILL),
SIGFUN(SIGSTOP),
// ...
{ .signo = 0, .signame = NULL }
};
#define SIGFORALL(_sig) \
_sig = siglist; _sig->signame != NULL; ++_sig
int
signame_to_signo(const char *signame)
{
struct sigfun *sig;
for (SIGFORALL(sig)) {
if (strcmp(sig->signame,signame) == 0)
break;
}
return sig->signo;
}
const char *
signo_to_signame(int signo)
{
struct sigfun *sig;
for (SIGFORALL(sig)) {
if (signo == sig->signo)
break;
}
return sig->signame;
}
UPDATE:
why not put for into SIGFORALL? –
tstanisl
For a few reasons ...
I've done that before (e.g.):
#define SIGFORALL(_sig) \
for (_sig = siglist; _sig->signame != 0; ++_sig)
SIGFORALL(sig) {
// do stuff
}
This tends to confuse certain IDEs and/or tools that parse the code without running it through the preprocessor.
It's also more difficult for programmers to quickly (without digesting the macro) skip over it.
They don't see a for and have trouble figuring out what SIGFORALL(sig) { does.
Is the macro a wrapper for if, for, or while?
With:
#define SIGFORALL(_sig) \
_sig = siglist; _sig->signame != 0; ++_sig
for (SIGFORALL(sig)) {
// do stuff
}
there is a better chance they can continue around the construct because they can understand (i.e. skip over) the for (...) [syntactically] without having to know what the macro is doing. That is, nobody has to "drill down" into the macro unless they wish to.
Another reason is that without the for in the macro, we can add extra code to the for loop's initialization and iteration expressions. It's more flexible.
For example, I've used a similar macro for linked list traversal and wanted to know the index/count of an element:
#define LLFORALL(_node) \
_node = nodelist; _node != NULL; _node = _node->next
int idx;
for (idx = 0, LLFORALL(node), ++idx) {
if (node->value == 5)
printf("found value at index %d\n",idx);
}
There's no absolute rule about this. Ultimately, it's a [personal] style preference.
Perhaps what you want instead is:
int s[3] = { SIGINT, SIGKILL, SIGSTOP };
signal(s[0], do_something);
I have a function like:
typedef struct
{
bool x;
bool y;
bool z;
} myStruct;
static void myFunction(const myStruct *pTomystruct_out)
{
if (pTomystruct_out->x == TRUE)
{
/*Do Something*/
}
}
Now for some debug purpose I want to add debug code to set the pointer parameter always to TRUE.
Within the function before the if statement I want to do something like:
pTomystruct_out.x = TRUE /*This is not the correct way*/
How to do this in the right way?
Thanks!
pTomystruct_out is a pointer, so you have to dereference that for manipulating what is pointed.
You can use * opetator to dereference:
(*pTomystruct_out).x = TRUE;
Also you can use -> operator where A->B means (*A).B:
pTomystruct_out->x = TRUE;
Also, this is not enough because the pointer pTomystruct_out is marked as const.
You can use a cast to non-const pointer for having it allow modifications.
((myStruct*)pTomystruct_out)->x = TRUE;
This is syntactically collect, but it may be dangerous to modify the object that is thought not to be modified. Creating a copy of the object and modifying the copy is safer.
typedef struct
{
bool x;
bool y;
bool z;
} myStruct;
#if 1 /* debug mode */
static void myFunction(const myStruct *pTomystruct_out_arg) /* change argument name */
{
myStruct pTomystruct_debug_temp = *pTomystruct_out_arg; /* make a copy */
myStruct *pTomystruct_out = &pTomystruct_debug_temp; /* declare a variable with original argument name */
pTomystruct_out->x = TRUE; /* modify the copy */
#else
static void myFunction(const myStruct *pTomystruct_out)
{
#endif
if (pTomystruct_out->x == TRUE)
{
/*Do Something*/
}
}
As mentioned in previous answer, the parameter is const, disabling modifications to that parameter. You probably don't want it to be const.
To add debug code, you can make use of macros. You can have a header file contain macros, like seen below:
#define DEBUG
Or:
#define DEBUG 1
Included a header with this macro allows you to write your function as follows:
static void myFunction(const myStruct *pTomystruct_out)
{
#ifdef DEBUG
pTomystruct_out.x = TRUE
#endif
}
If you used the latter macro, #define DEBUG 1 (which I recommend), you can use an if-statement instead:
static void myFunction(const myStruct *pTomystruct_out)
{
#if DEBUG
pTomystruct_out.x = TRUE
#endif
}
I recommend using #define DEBUG 1, because then you don't have to comment out the macro whenever you don't want it. You can just set it to 0.
If you don't want a header file, you can use the -D flag using gcc, like gcc <INPUTFILE> -DDEBUG.
Hi All here is my specific case:
service.h:
typedef struct {
uint8_t (*function1)(void);
uint8_t (*function2)(void);
} const service_struct_t;
extern service_struct_t service_api ;
service.c:
#include "service.h"
static uint8_t foo(void){
return 13+6;
}
static uint8_t bar(void){
return 7*6;
}
service_struct_t service_api = {
.function1 = foo,
.function2 = bar,
};
I need to stub (to mock, to replace) these functions but I have no right to change that original code. I'm using gcc to compile the unit tests. I've failed to:
use the --wrap option of gcc straight on foo and bar since they are static to source.c :
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
uint8_t __real_foo(void);
uint8_t __wrap_foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_foo();
}
}
/* same for bar */
use the --wrap option of gcc onto the service_api object symbol because it's not a function
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
uint8_t __real_service_api ;
uint8_t __wrap_service_api = {
.function1 = foo,
.function2 = bar,
}
static uint8_t foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_service_api.function1();
}
}
/* same for bar */
simply reassign the service_api member functions since the structure is constant and already assigned.
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
service_struct_t backup_service_api = {
.function1 = service_api.function1;
.function2 = service_api.function2;
}
service_struct_t stub_service_api = {
.function1 = foo;
.function2 = bar;
}
uint8_t foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_foo();
}
}/* same for bar */
void service_poke_stub(bool_t enable_stubs){
if(enable_stubs){
service_api.function1 = stub_service_api.function1
service_api.function2 = stub_service_api.function2
}else{
service_api.function1 = backup_service_api.function1
service_api.function2 = backup_service_api.function2
}
}
thanks already for your help
You can't mock the functions in the structure, as you already found out.
So it depends on what you like to test:
If you want to test whether the structure contains the correct functions, the module service.c is your module-under-test and should be used as is. You need to check the correctness by watching what is done by the functions.
If you want to test that the structure is used correctly, you will mock the whole module. Now you are free to put in it whatever you want.
If your source code does not allow this, the design is bad for testing. This is often the case when the architecture is not done with testability in mind.
I'm playing around with the preprocessor and c. Trying to implement my own event and hierarchy system.
However I'm facing a problem. I'm trying to statically define my "modules" which can be initialized, and some events which also are statically defined in advance. For the events I'm using COUNTER which works beautiful. But I don't want to mix up module id's and event id's.
So a simplified version of what I'm trying to achieve:
hierarchy.h
#define HIERARCHY_DEFINE(NAME) int hierarchyId = __COUNTER__
event.h
#define EVENT_REGISTER(NAME) int eventId = __COUNTER__
main.c
#include "event.h"
#include "hierarchy.h"
EVENT_REGISTER(EventOne);
HIERARCHY_DEFINE(ModuleOne);
EVENT_REGISTER(EventTwo);
int main(void){
printf("events(%d, %d) modules(%d)\n",EventOne,EventTwo,ModuleOne);
return 1;
}
This will print out:
events(0, 2) modules(1)
When I'm trying to achieve:
events(0, 1) modules(0)
I've looked around and people saying I can't create a counter on my own. And seen the boost counter, but that doesn't achieve what I want either.
Does anybody have an idea how I could handle this situation?
Thanks!
Edit:
slight adition of what my code actually looks like
struct Event{
uint8_t eventId;
uint8_t * data;
const char * description;
};
#define EVENT_REGISTER(eventName, desc)\
static Event eventName = {.eventId = __COUNTER__, .data = 0, .description = desc }
EVENT_REGISTER(Timer_5, "Timer 5 hZ");
Unless you have additional requirements for the identifiers, the following will do:
definitions.inc
EVENT_REGISTER(Timer_5, "Timer 5 Hz")
EVENT_REGISTER(Timer_10, "Timer 10 Hz")
MODULE_REGISTER(Module_SSH)
MODULE_REGISTER(Module_NCO)
#undef EVENT_REGISTER
#undef MODULE_REGISTER
app.c
#define EVENT_REGISTER(a, d) a,
#define MODULE_REGISTER(a)
enum events {
#include "definitions.inc"
};
#define EVENT_REGISTER(a, d)
#define MODULE_REGISTER(a) a,
enum modules {
#include "definitions.inc"
};
struct Event {
uint8_t event_id;
uint8_t *data;
const char *description;
};
#define MODULE_REGISTER(a)
#define EVENT_REGISTER(a, d) static struct Event Event_##a = { .event_id = a, \
.data = NULL, \
.description = d \
};
#include "definitions.inc"
int main (int argc, char **argv)
{
printf("events(%d, %d) modules(%d)\n", Timer_10, Timer_5, Module_SSH);
return EXIT_SUCCESS;
}
You must either:
assign ids at runtime,
assign ids by hands
or keep all events and modules definitions in one place.
Consider that you have a.c and b.c, and they contains some EventA and EventB definitions respectively. As they are separate compilation units, there is no way compiler can assign non-overlapping ids to them. Compiling b.c, it doesn't even know there is another a.c where id 1 is already assigned.
For the first one, have a RegisterEvent function like so:
void RegisterEvent(Event* event){
static int nextEventId = 0;
event->eventId = nextEventId;
}
And call it for every Event you need.
Second one is obvious, but tedious and error prone.
For the third solution, you can use an X macro.
Have a X-list of all your events:
#define EventList \
Event(FirstEvent, "FirstEvent") \
Event(Timer_1, "Timer 1 hZ") \
...
Event(Timer_5, "Timer 5 hZ")
Now, in a header there you are going to declare all your events (say, events.h):
#define Event(name, desc) EventID ## name,
enum EventID{
EventIDZero = 0,
EventList
EventIDCount
};
#undef Event
#define Event(name, desc) \
extern Event name;
EventList
#undef Event
And in a single compilation unit where your event definitions will reside (say, events.c):
#include "events.h"
#define Event(name, desc) \
Event name = {.eventId = EventID ## name, .data = 0, .description = desc };
EventList
#undef Event
After macro expansion, events.c looks like (slightly edited for readability):
enum EventID{
EventIDZero = 0,
EventIDFirstEvent, EventIDTimer_1, EventIDTimer_5,
EventIDCount
};
extern Event FirstEvent;
extern Event Timer_1;
extern Event Timer_5;
Event FirstEvent = {.eventId = EventIDFirstEvent, .data = 0, .description = "FirstEvent" };
Event Timer_1 = {.eventId = EventIDTimer_1, .data = 0, .description = "Timer 1 hZ" };
Event Timer_5 = {.eventId = EventIDTimer_5, .data = 0, .description = "Timer 5 hZ" };
Same thing goes for modules.
I've a huge C project with a module reading and managing configuration data. If I have to add a new configuration parameter, I'll have to edit several functions, e.g. as pseudo-code:
void read_configuration(config *c) {
read_param("p1", c->p1);
read_param("p2", c->p2);
read_param("p3", c->p3);
/* ... */
}
void dump_configuration(config *c) {
dump_param("p1", c->p1);
dump_param("p2", c->p2);
dump_param("p3", c->p3);
/* ... */
}
Is there a way to ensure by macro at compile time, that each location has at least the same count of parameters? I thought of making dump_param some kind of macro counting the invocations and then add something like
#if nr_read != nr_dump
#error "You forgot something, idiot!"
#endif
at the end of the module. I can't find a method to make the macro count its invocations, though...
Since the list of parameters is the same in both functions, how about factoring that out and avoid any possible mismatch ?
Using X-macros
#define X_CONFIG_PARAMS(config) \
X("p1", (config).p1) \
X("p2", (config).p2) \
X("p3", (config).p3)
void read_configuration(config *c) {
#define X(name, param) read_param(name, ¶m);
X_CONFIG_PARAMS(*c)
#undef X
}
void dump_configuration(config *c) {
#define X(name, param) dump_param(name, ¶m);
X_CONFIG_PARAMS(*c)
#undef X
}
Using function pointers
void alter_config(config *c, void(*func)(char const *name, Param *param)) {
func("p1", &c->p1);
func("p2", &c->p2);
func("p3", &c->p3);
}
void read_configuration(config *c) {
alter_config(c, read_param);
}
void dump_configuration(config *c) {
alter_config(c, dump_param);
}
Using an array and offsetof
struct param_info {
char const *name;
size_t config_offs;
};
param_info allParams[] = {
{"p1", offsetof(config, p1)},
{"p2", offsetof(config, p2)},
{"p3", offsetof(config, p3)}
};
void read_configuration(config *c) {
size_t paramCount = sizeof allParams / sizeof *allParams;
for(size_t i = 0; i < paramCount; ++i) {
Param *p = (Param*)((char*)config + allParams[i].config_offs);
read_param(allParams[i].name, p);
}
}
void dump_configuration(config *c) {
size_t paramCount = sizeof allParams / sizeof *allParams;
for(size_t i = 0; i < paramCount; ++i) {
Param *p = (Param*)((char*)config + allParams[i].config_offs);
dump_param(allParams[i].name, p);
}
}
I would rather let the preprocessor write the code in the first place.
It could look something like this:
Define the list of parameters in a separate file, say parameters.inc:
PARAM (p1)
PARAM (p2)
...
Then in the source code locally define the macro PARAM as required and let the preprocessor include and expand the contents of parameters.inc:
void read_configuration(config *c) {
#define PARAM(NAME) read_param(#NAME, c->NAME);
#include "parameters.inc"
#undef PARAM
}
void dump_configuration(config *c) {
#define PARAM(NAME) dump_param(#NAME, c->NAME);
#include "parameters.inc"
#undef PARAM
}
I don't think you can do this at compile time without ugly hacks.
What you could do: add a test to your test suite which replaces the header that contains the read_param() and dump_param() macros so they generate code which only updates a counter. Then, in the main() function of that test, place an assertion that compares both counters and fails if they're not equal.
You do have a test suite and run it at compile time, right? ;-)
However, I do agree with the comment that it's probably better to do this differently. In an approach called "table-driven programming", you turn the macro definition and data definition on their head (that is, you have the #define in your .c file and the use of the macro in the header rather than the other way around), you don't have this problem. Poul-Henning Kamp, of FreeBSD fame, explains very well how to that here.