Clark Gaebel
Clark Gaebel

Reputation: 17988

Static initialization in C

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.

Upvotes: 1

Views: 4555

Answers (4)

Christoph
Christoph

Reputation: 169763

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.

Upvotes: 4

Steve Emmerson
Steve Emmerson

Reputation: 7832

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.

Upvotes: 0

Jan B. Kjeldsen
Jan B. Kjeldsen

Reputation: 18061

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

Upvotes: 1

ondra
ondra

Reputation: 9351

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).

Upvotes: 0

Related Questions