我在跨多个文件读取和写入结构时遇到问题。本质上,我需要写入结构中的变量,稍后在计时器中断期间检查这些变量。发生这种情况时,新的计时器值将作为该结构中的成员。目前我在 while(1) 循环中硬设置这些定时器值,但稍后这些值将从某些算法中获取。我不太确定我是否正确地读取了结构成员。该项目编译,但在运行时,它将计时器设置为随机值。然而,GDB degugging 确认它们是正确的。
如果我直接设置定时器值,一切正常。
这是一个基于 ARM cortex M4 的嵌入式项目。
我在 types.h 中定义了一个结构
#ifndef __TYPES_H
#define __TYPES_H
typedef struct { uint32_t a; uint32_t b; uint32_t c;} myStruct;
#endif
然后在main.c中
#include <types.h>
myStruct hello
int main(void){
while(1){
hello.a = 10;
hello.b = 43;
hello.c = 98;
}
}
然后在interrupt.c中
#include <types.h>
myStruct hello
int count = 0;
void timer_IRQHandler(void){
if(interrupt != RESET){
switch(count){
case 0:
timerSet(hello.a); // if i just put a number here, it works fine
count++;
break;
case 1:
timerSet(hello.b);
count++;
break;
case 2:
timerSet(hello.c);
count++;
break;
}
resetInterrupt();
}
}
--- 解决方案 ---
好的,我已经想通了,可以四处移动东西,但除此之外它是这样工作的:
类型.h
#ifndef __TYPES_H
#define __TYPES_H
typedef struct { uint32_t a; uint32_t b; uint32_t c;} myStruct;
#endif
然后在main.c中
#include <types.h>
myStruct volatile hello = {10,10,10};
int main(void){
while(1){
hello.a = 10;
hello.b = 43;
hello.c = 98;
}
}
然后在interrupt.c中
#include <types.h>
extern myStruct hello
int count = 0;
void timer_IRQHandler(void){
if(interrupt != RESET){
switch(count){
case 0:
timerSet(hello.a); // if i just put a number here, it works fine
count++;
break;
case 1:
timerSet(hello.b);
count++;
break;
case 2:
timerSet(hello.c);
count++;
break;
}
resetInterrupt();
}
}
extern好像解决了跨文件获取struct的问题,还有{10,10,10}的初值声明,我觉得解决了一些内存分配问题。代码可以编译,但没有它就不能保持正确的值。我还不知道 volatile 做了什么,如果我删除它没有区别。我将继续阅读的内容。
最佳答案
在头部声明
extern myStruct hello;
并在一个cpp中定义它
myStruct hello;
关于C - 跨多个文件的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24514783/