This is a follow-up question to the accepted answer to this other SO article. I think this stands alone in its own right, which is why I posted it.
I'm trying to "collect" structs defined in different modules into an ELF section. I'm doing this by way of GCC compiler __attributes__
. I'm not sure what's preventing this from working.
There are a number of related questions on SO and I've tried some of their ideas with the idea that something small in my code is the issue. For example, this one.
Update (I simplified the code some more)
#include <stdio.h>
#define INFO_NAME(counter) INFO_CAT(INFO_, counter)
#define INFO_CAT(a, b) INFO_DUMMY() a ## b
#define INFO_DUMMY()
#define DEFINE_INFO(data...) \
const static struct mystruct INFO_NAME(__COUNTER__) \
__attribute((__section__("info"))) \
__attribute((__used__)) = { data } \
struct mystruct
{
char name[255];
int (*on_init) (int num1);
int (*on_do_something) (int num1);
};
extern struct mystruct __start_info[];
extern struct mystruct __stop_info[];
static int _print_number(int x)
{
printf("%d\n", x);
}
DEFINE_INFO(
.name = "mary",
.on_init = _print_number,
.on_do_something = _print_number
);
DEFINE_INFO(
.name = "joe",
.on_do_something = _print_number
);
DEFINE_INFO(
.name = "bob",
.on_do_something = _print_number
);
int main(void)
{
struct mystruct *iter = &__start_info;
for ( ; iter < &__stop_info; ++iter)
{
printf("element name: %s\n", iter->name);
if (iter->on_init != NULL)
{
iter->on_init(1);
}
if (iter->on_do_something != NULL)
{
iter->on_do_something(2);
}
}
return 0;
}
What I am seeing:
$ ./a.out
element name: mary
1
2
element name:
element name:
element name:
Segmentation fault (core dumped)
What I expected to see:
$ ./a.out
element name: mary
1
2
element name: joe
2
element name: bob
2