【发布时间】:2016-08-01 11:27:58
【问题描述】:
我正在做一个项目,我需要在使用“extern”的主函数中使用在某个文件(比如 mylib.c)中声明的一个变量。所有标题都包含在警戒词中,以避免多次包含。 该变量是一个结构(在 mylib.h 中定义),其成员只有浮点数和整数。它在 main 函数的开头被初始化。
进入主循环,做一些工作后,一些不关心的成员得到随机值。
所以,我从 main 中的声明中删除了 extern,而是将它放在 mylib.c 中的声明中。它奏效了。
Sim808.h
#ifndef _SIM808_H
#define _SIM808_H
typedef struct{
uint8_t GPRS_Active;
float gsm_latitude;
float gsm_longitude;
}SIM808;
void sendCmd(const char cmd[]);
void sim808_init(void);
void parse_gsm_location(uint8_t* line);
#endif
Sim808.c
#include "sim808.h"
SIM808 sim808;
void parse_gsm_location(uint8_t* line)
{
uint8_t commas=0,index=0;
uint16_t err;
if((err=atoi((const char*)line+12))!=0)
{
printf("No coordinates received\n");
if(err==404 || err==601)
sim808.GPRS_Active=0;
return;
}
while (line[index]!= '\0' && index <50)
{
if(line[index]==',')
{
commas++;
switch (commas)
{
case 1:
sim808.gsm_longitude=atof((const char*)(line+index+1));
printf("Long:%f\n",sim808.gsm_longitude);
break;
case 2:
sim808.gsm_latitude=atof((const char*)(line +index+1));
printf("Longitude%f Latitude%f\n",sim808.gsm_longitude,sim808.gsm_latitude);
break;
case 3:
sscanf((const char*)(line+index+1),"%4d/%2d/%2d", (int*)&sim808.gsmDate.year,(int*)&sim808.gsmDate.month,
(int*)&sim808.gsmDate.day);
break;
case 4:
sscanf((const char*)(line+index+1),"%2d/%2d/%2d",
(int*)&sim808.gsmTime.hours,(int*)&sim808.gsmTime.minutes,(int*)&sim808.gsmTime.seconds);
break;
}
}
index++;
}
}
main.c
#include "sim808.h"
extern SIM808 sim808;
int main(void)
{
uint8_t response[150];
//init functions
while(1)
{
if(sim808.GPRS_Active==1)
{
sendCmd("AT+CIPGSMLOC=1,1\r\n");
HAL_UART_Receive(&huart4,response,2,60000);//max response time is 1 min
HAL_UART_Receive(&huart4,response,150,1000);//we dont need first 2 chars
parse_gsm_location(response);
memset((void*)response,0,150);
}
else
sim808_init();
}
}
如您所见,成员 GPRS_Active 在我的代码中只能接收 1 或 0。 使用 printf,它在第一次迭代后变成了 242。 有人可以解释吗?这可能是编译器错误吗? 谢谢。
【问题讨论】:
-
根据您提供的数据的匮乏,我的水晶球猜测您的代码存在问题,因为这是编译器错误的可能性非常小。要获得真正的答案,请发布MCVE
标签: c compiler-errors global-variables extern stm32