Home > OS >  Dynamic initialization in C when you don't control main
Dynamic initialization in C when you don't control main

Time:02-04

I have a rather idiosyncratic C 14 initialization issue. I'm linking against a C library which provides main(). That library makes use of a global array that I'm meant to define, something like this:

extern int array[];

int main(void)
{
    for (int i = 0; array[i] != -1; i  ) {
        printf("%d\n", i);
    }
}

The expected use is to initialize the array, e.g. int array[] = {1, 2, 3, -1}. But I want to be able to dynamically initialize it. I'm using C 14, so my thought was to create a global object with a constructor that writes to the array, like this:

int array[2];

struct Init {
    Init() {
        array[0] = 1;
        array[1] = -1;
    }
}

Init init;

But the C 14 standard says this:

It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized.

Am I reading this correctly that it's possible that when main() runs, my object won't yet have been constructed, meaning that my array won't be initialized (or rather, will be default initialized, not by my class)?

If so, is there any way around this? I have no control over the library which provides main(). Am I out of luck in wanting to set the array's value at startup time, before main() runs?

CodePudding user response:

it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit

Emphasis "any function or variable". The "variable" part includes, of course, the global variable in question.

In other words, the initialization is guaranteed to occur before odr-use of the variable. Problem solved.

So, as soon as anything in your C program sneezes in the direction of "any function or variable" in the translation unit where the global array is defined, they will materialize into existence.

You are guaranteed before the array is odr-used, the initialized of init takes place, since it's in the same translation unit, and that will take care of whipping array into shape, before it gets odr-used.

  • Related