Initializer element is not constant for declaring time function globally

本小妞迷上赌 提交于 2020-07-10 07:23:09

问题


I have my C program with time function declared globally as follows:

time_t t = time(NULL);
struct tm *tm = localtime(&t);
time(&rawtime);
void file_name()
{
   sprintf(buffer,"data/log_%d.%d_%d:%d:%d",tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
   char *p = buffer;
   for(;*p;++p)
  {
     if(*p == ' ')
     *p = '_';
  }
  printf("%s",buffer);
  }
}

void create_file()
{
  file_name();
  fptr = fopen(buffer,"w"); 
}

void read_data();
{
.
.
.
.

sprintf(buffer1,"_%d:%d:%d",tm->tm_hour,tm->tm_min,tm_sec);
fprintf(fptr,"%d.%d_%d:%d:%d,%d",tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
close_file();

}


int main()
    {



       read_data();

       .
       .


       return 0;
    }

Since I want to use tm in two more functions like one is filename(); and similarly another function called read_data(); in the program for printing the month, date and etc. I want to declare these globally. But when I compile the program, it gives an error called initializer element is not constant at time_t t = time(NULL); and struct tm *tm = localtime(&t); Can anyone help me in this thanks in advance.


回答1:


The following code:

time_t t = time(NULL);
struct tm *tm = localtime(&t);

is not valid. You cannot call a function when initializing a global variable in C. The initializer element (ex. in time(NULL) for t) is not constant (compiler does not know it's value when compiling, ei. for time(NULL) the compiler does not know what time it is when the program is run, when the compiler is compiling the program).
Also you cannot call do a global function call, you must be in some function to call anything, the code:

 time(&rawtime);

is also not valid.

You can declare these variables as global variables and initialize them in main(). All global variables that don't have any initialization are initialized with 0 or NULL. Example:

time_t t;
struct tm *tm;
...
int main() { 
   // first things first - initialize global variables to a known state
   t = time(NULL;
   tm = localtime(&t);
   time(&rawtime);
   // other things to do
   ...
   read_data();
   ...
}


来源:https://stackoverflow.com/questions/49731102/initializer-element-is-not-constant-for-declaring-time-function-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!