tags:

views:

131

answers:

4

I want to have code that looks something like this...

static linked_list* globalListHoldingAllSortsOfGoodies = initialize_linked_list();

/* [In a different file...] */
static int placeholder = add_to_global_list(goodies);

But non-constant initialization is impossible in C.

Is there some way to get the same affect without breaking C89?

The point is to have different things "automatically register" themselves into the global list by declaring the goodies with a macro that also uses placeholder.

A: 

No, there is no such thing. You can initialize static variables with static data. Adding to the list is not 'static'. I believe what most people do is to write a preprocessor that scans the source files, find the things you want to have in a 'global list' and then generates a .c file with the appropriate data (e.g. NULL-terminated statically initialized table).

ondra
There is NO way you could do this in a different file. At least not in .o file as there is no way to 'initialize' the list (or table). And I don't think there is enough macro magic to initialize it through a .h file.
ondra
+1  A: 

Well, you could initialize the placeholder in the main method :-)

Jan B. Kjeldsen
Not macro-able.
Clark Gaebel
Your needing this in macros why?
Earlz
A: 

As you've noticed, C doesn't have this capability. If you can't do it outside of C (by generating the C code), then an alternative would be to create an initialize() function for each module that needed it and ensure that the functions were called at the appropriate time.

Steve Emmerson
+4  A: 

You can build a linked list from static data. In ANSI C89 (aka ISO C90), it could look like this:

struct node
{
 int data;
 struct node *next;
};

struct node nodes[] = { { 42, &nodes[1] }, { 137, 0 } };
struct node *list = nodes;

In ISO C99 (adopted by ANSI in 2000), you can additionally use compound literals, eg

struct node *list = &(struct node){ 42, &(struct node){ 137, 0 } };

Mixing statically allocated nodes with dynamically allocated nodes is problematic as freeing the former will result in undefined behaviour, so it will be necessary to keep track of which nodes belong to which group.

Christoph
That's a crafty idea. How do I do it for auto-registration scenarios? Like, in foo.c I have code to add to a list declared in bar.h, and in baz.c I also add to the list, etc.Basically, I want to decentralize the "list adding", and all the data will be static.
Clark Gaebel