用于全局声明时间函数的初始化器元素不是常量

用于全局声明时间函数的初始化器元素不是常量

本文介绍了用于全局声明时间函数的初始化器元素不是常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C程序具有如下声明的全局时间函数:

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;
    }

因为我想在另外两个函数中使用tm,其中一个是filename();同样,另一个名为read_data()的函数;在打印月份,日期等的程序中.我想全局声明它们.但是,当我编译程序时,它给出了一个错误,称为time_t t = time(NULL);struct tm *tm = localtime(&t);的初始化元素不是恒定的.

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.

推荐答案

以下代码:

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

无效.在C中初始化全局变量时,不能调用函数.初始化元素(例如,在time(NULL)中,对于t)不是常量(编译器不知道其值,对于time(NULL),编译器不知道).不知道何时运行程序,何时编译器正在编译程序).
另外,您不能调用做全局函数调用,您必须在某个函数中调用任何东西,代码:

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

也是无效的.

您可以将这些变量声明为全局变量,并在main()中对其进行初始化.所有没有任何初始化的全局变量都用0或NULL初始化.示例:

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();
   ...
}

这篇关于用于全局声明时间函数的初始化器元素不是常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 06:17