私は、ある関数(例えば、mylib.c)で宣言されている変数を 'extern'を使ってmain関数で使う必要があるプロジェクトに取り組んでいます。複数のインクルードを避けるために、すべてのヘッダーにガードワードが含まれています。 変数はmylib.hで定義されている構造体で、メンバーは浮動小数点数と整数のみです。これはmain関数の先頭で初期化されます。STM32上のCでのグローバル変数
メインのループに入り、何らかの作業をした後、関係のないメンバーの中にはランダムな値があります。
したがって、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](http://stackoverflow.com/help/mcve) –
を投稿してください。 – rost0031