Variable estática en un ámbito de archivo

I have used a static variable "EnvVarIsSet" in file scope in a certain abc.cpp archivo de la siguiente manera

#include <env.h>
static bool EnvVarIsSet = IsEnvironmentVariableSet();

La rutina IsEnvironmentVariableSet() is an extern routine and declared and defined in other files (env.h & env.cpp). Somewhere down in the file abc.cpp, in some routine, I have used this variable (and also at other places in this file)

if( EnvVarIsSet )
   //do something

Does this mean, during runtime, whenever it encounters the variable EnvVarIsSet in abc.cpp archivo, IsEnvironmentVariableSet() routine will be called? Or does static variable as the one above will only work with constants (i.e. static binding, e.g. const bool EnvVarIsSet = false)?

preguntado el 27 de noviembre de 13 a las 05:11

1 Respuestas

La declaración

static bool EnvVarIsSet = IsEnvironmentVariableSet();

will be executed once in your compilation module. And every time the value ofEnvVarIsSet será lo mismo.

respondido 27 nov., 13:07

Additionally, it will be executed at some unspecified time before main() is called. Other static initializer may have run, or they may not have run yet. - chwarr

@Nik At compile time how will it know what IsEnvironmentVariableSet() would return? Wouldn't it be possible only at runtime? - con hielo

@c45207 I tried using the static in two different cpp files belonging to two different libraries. In one of them it was called before main() and in the other, after I launched an application. Not sure, may be something to do with loading libraries on demand. - con hielo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.