static变量的初始化问题
我现在有这些文件:main.c,test.c,test.h。其中main.c包含test.h
我现在在main.c里有一个循环,
while( image_buf )
{
image_process( int width, int height, pimage_t image );
}
其中pimage_t是自定义的图像指针类型,image_buf就是pimage_t类型,代表从视频中读入的每帧图片
我要在image_process里对读入的image进行缩放,缩到原始尺寸的长宽各一半,然后把缩放后的图片(image_scale)写入定义好的文件中(以下代码都是在image_process函数中实现的,该函数的实现在test.c中):
FILE *stream;
stream = fopen("C:\\mydir\\test.y", "wb+");
fwrite( image_scale, 1, width_scale * height_scale, stream );
这有一个问题,就是每次进入while循环都会调用image_process(),然后对文件指针stream初始化,文件指针每次都是定位到文件的首地址,上次写入的数据会被自动清零。
我想到用static
static FILE *stream;
stream = fopen("C:\\mydir\\test.y", "wb+");
fwrite( image_scale, 1, width_scale * height_scale, stream );
这样还是不行,仍然会清零,然后我这样做:
static FILE *stream = fopen("C:\\mydir\\test.y", "wb+");
编译器(VC6)报错,错误信息:initializer is not a constant
我不知道.c和.cpp有啥区别,c语言里的static变量该怎么给值,谢谢各位给点帮助!
[解决办法]
如果不存在并发调用可以这样
static FILE *stream = NULL;
if (stream == NULL)
stream = fopen("C:\\mydir\\test.y", "wb+");
fwrite( image_scale, 1, width_scale * height_scale, stream );