![](/img/trans.png)
[英]How to get a typedef struct to work across multiple files files? error: invalid use of undefined type 'struct data'
[英]C - Struct across multiple files
我在跨多个文件读写结构时遇到问题。 本质上,我需要写入结构中的变量,这些变量随后会在计时器中断期间进行检查。 发生这种情况时,新的计时器值将被视为该结构中的成员。 目前,我很难在while(1)循环中设置这些计时器的值,但是稍后这些值将从某种算法中获取。 我不确定我是否正确读取了struct成员。 该项目进行编译,但是在运行时,它将计时器设置为随机值。 GDB进行脱轨确认它们是正确的。
如果我直接设置计时器值,那么一切正常。
这是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();
}
}
-解决方案-
好的,我已经弄清楚了,可以随处移动东西,但否则它的工作原理如下:
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 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似乎已经解决了跨不同文件获取结构的问题,并且{10,10,10}的初始值声明已经解决了一些内存分配问题。 代码可以编译,但是没有它就无法保存正确的值。 我不知道什么是挥发性的,如果我除去它也没有区别。 我会继续读下去。
在标题中声明
extern myStruct hello;
并以一个cpp定义它
myStruct hello;
您是否对编译器在while循环中优化访问存在问题? 由于编译器不知道其他执行线程正在查看hello的值,因此也许只是不编写它们? 尝试将volatile添加到“外部myStruct hello”中,或查看混合程序集输出,并查看其是否写入了hello结构。
看这里
实际上,您两次声明了该结构(使用相同的名称),这就是代码无法正常工作的原因。 定义一次(在main中说),然后使用extern在其他文件中引用它。
extern myStruct hello;
在我看来,您的timer_IRQHandler
在内核中作为中断例程被调用。 如果为true,可能永远不会调用main。
我会尝试静态初始化您的结构,而不是依靠main
来初始化它。 例如:
myStruct hello = { 10, 43, 98 };
是的,如果有多个文件引用,则应在标头中将其声明为extern,并在源文件中仅对其定义/初始化一次。
至于易失性,它用于设备寄存器或内存映射的地址,如果读取两次,它们可能不会给出相同的答案。 它告诉编译器不要尝试优化该内存位置的多次读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.