I am trying to initialize a C struct using the following code:
/* header file */
typedef struct _funky {
int func_id; /* I know this should be intptr_t, but ignore for now ... */
char func_name[MAX_FUNC_NAME_LEN];
} Funky;
double func1(double d1, double d2, double d3);
double func2(double d1, double d2, double d3);
double func3(double d1, double d2, double d3);
double func4(double d1, double d2, double d3);
/* .c file */
Funky fk[4] = {
{(int)func1, "func1"}, /* <- gcc barfs here ... */
{(int)func2, "func2"},
{(int)func3, "func3"},
{(int)func4, "func4"}
};
When I attempt to compile this (gcc 4.6.3), I get the following errors:
error: initializer element is not constant
error: (near initializer for 'fk[0].func_id')
How I can fix this error?
[[Edit]]
After a brief chat with ouah, I have found the reason for this error - it is to do with the function definitions being used to initialize the array. Some of the definition are in different translation units, and others in different modules. All of which means (IIUC) that the functions will not be defined at compile time.
Short of writing an initialization function (which will require extensive mod in existing code) I'm not sure how to solve this - and I'm not sure how it compiled under previous versions of gcc either.
intptr_tis not guaranteed to be able to hold a function pointer value without loss of information, though it's likely to be able to. (Probablyuintptr_twould make slightly more sense thanintptr_t.)