gpt4 book ai didi

c++ - switch 语句中的静态变量

转载 作者:太空狗 更新时间:2023-10-29 23:03:41 28 4
gpt4 key购买 nike

我正在使用 c 开发一个 keil 项目。在我的一个文件中,我在顶部将一些变量定义为静态。我在这个文件的一些函数中使用它们,我也在 switch/case 语句中使用它们。例如:

在定义变量的顶部:

static uint8_t* imageData = 0;
static uint32_t height = 0;
static uint32_t width = 0;
static uint32_t stride = 0;

在代码中间:

switch (pMsg->MsgId)
{

case WM_CREATE:
{
CAMERA_Init();
AMProcessor *processor = new AMProcessor();

struct block blocks[2] = {
{2, 240, 160},
{2, 160, 120}
};
processor->initBlocks(blocks, 2);
stride = 480; //sample_image.width;
processor->Initialize(480, 272, 480, InputTypes::CHROMA_MOBILE, InputTypes::RGB);
BSP_LED_Toggle(LED3);

while(1){
const PictureOutput* picOut = processor->ProcessImage((uint8_t *)CAMERA_FRAME_BUFFER);
break;
}
}

在底部附近,我有几个函数也使用这些变量。但是,我收到警告,告诉我顶部定义的 4 个变量已初始化但从未被引用。如果它们不是静态的,那么我不会收到此警告,但会收到硬故障错误(我正试图摆脱)。

所以我的问题是,为什么没有引用这些?明明跟静态定义有关系,可是静态定义怎么不允许引用这些呢?

需要澄清的是:我在所有人身上都收到了这条信息,甚至是大步前进。警告:#177-D:变量“imageData”已声明但从未被引用

我在底部有一个使用所有这些变量的函数,如下所示:

bool ReadImageFromPgmFile(const char* pFileName, uint32_t &height, uint32_t &width, uint8_t*& ImgData) {
if (pFileName == 0) {
return false;
};

// read data from file
if (strstr(pFileName, ".pgm") || strstr(pFileName, ".PGM")) {
FILE *pPgmFile = fopen(pFileName, "r");

if (pPgmFile == NULL) {
fprintf(stderr, "Cannot open PGM file '%s'.\n", pFileName);
return false;
};

char x = fgetc(pPgmFile);
char y = fgetc(pPgmFile);

if (x != 'P' || y != '5') {
fprintf(stderr, "Invalid PGM file '%s'.\n", pFileName);
return false;
};

uint32_t maxvalue;
fscanf(pPgmFile, "%d", &width);
fscanf(pPgmFile, "%d", &height);
fscanf(pPgmFile, "%d", &maxvalue);

if (maxvalue > 255) {
fprintf(stderr, "File '%s' has incorrect format.\nOnly 8-bit PGMs are supported by this reader.\n", pFileName);
return false;
};

ImgData = new uint8_t[width*height];
memset(ImgData, 0, width*height);
fgetc(pPgmFile); // skip new line character
uint32_t nPixelsRead = fread(ImgData, 1, width * height, pPgmFile);
fclose(pPgmFile);

if (nPixelsRead != width * height) {
fprintf(stderr, "PGM file '%s' does not contain all pixels.\n", pFileName);
return false;
};

return true;
}

return false;
};

最佳答案

方法声明隐藏了静态heightwidth 变量。

bool ReadImageFromPgmFile(const char* pFileName, 
uint32_t &height,
uint32_t &width,
uint8_t*& ImgData) {

在此方法中使用heightwidth 将引用局部参数而不是静态变量。我看不到对 imageData 的任何引用,尽管使用了一个 ImgData 参数。

此上下文中的 static 关键字意味着变量仅对声明它的编译单元可见。删除 static 关键字使其成为全局变量;整个程序都可以访问。编译器无法(或不愿意)推断全局变量的使用,因此您不会收到警告。

关于c++ - switch 语句中的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24864970/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com