It is possible to initialize a static variable using the call function

Is it possible?

static bool initialize()
{
  TRC_SCOPE_INIT(...); 
  ...
}

static bool initialized = initialize();

In short, I need to call a series of macros as soon as possible (to initialize debugging messages) (before starting thread X, and I have no way to know when thread X started).

+5
source share
4 answers

When I initially looked at the question, it was tagged with both C and C ++. The code can be C or C ++, because it boolis a type in C99 and C11, as well as in C ++ (almost in C, a heading boolneeds a heading <stdbool.h>).

Answers for two tags:

  • In C ++, yes.

  • In C no.

This is not the same language. If you need a demo, this is also a good example, like anyone.

+6
source

GCC ( clang), __attribute__((constructor)):

static bool initialized = false;

__attribute__((constructor))
static void initialize(void) {
    initialized = true;
    // do some other initialization
}

int main(int argc, char **argv) {
    // initialize will have been run before main started
    return 0;
}
+4

, "" , , . , . undefined - .

- . , undefined, , . "" , .

+1

(Since you mentioned threads, I'm going to assume that you have POSIX stream functions at your disposal.)

There is a function for this purpose pthread_once. Anywhere you need to be sure that it is initializealready called, write:

pthread_once(&init_once, initialize);

where is init_oncedetermined by the static duration of storage and, possibly, with external communication, if necessary, how pthread_once_t init_once.

+1
source

All Articles