嵌入式 C 使用来自复杂结构的标志
Embedded C utilizing a flag from a complex structure
在源文件inv_mpu.c中有一个结构定义gyro_state_s
和一个文件作用域变量声明:
static struct gyro_state_s st = {
.reg = ®,
.hw = &hw,
.test = &test
};
嵌套在这个结构中的是一个成员st.chip_cfg.bypass_mode
,我希望通过另一个文件访问它。
问题:如何在另一个文件中读取此标志 st.chip_cfg.bypass_mode
的状态?
我已经尝试了 extern struct gyro_State_s st ;
,但是当我在 if(!st.chip_cfg.bypass_mode)
中测试时仍然无法识别。
将结构放入共享 header 中,该结构包含在两个文件中。
extern 表示:'this is defined/instantiated elsewhere'
由于其下的结构不会编译为任何物理代码(结构的实例会编译,结构本身只是描述了如何创建它的实例)你只需要在两者中定义相同的结构文件,最好将结构放在共享 header 中,然后在需要结构的两个文件中包含 header。
试图暴露所有st
及其定义只是为了访问这个标志是一个糟糕的设计,应该避免。 Globals are always bad,在这种情况下,您将不必要地使 st
的所有内部结构对整个程序可见。
inv_mpu.c 已经有一个函数 mpu_set_bypass()
在使用之前被调用,所以必须在某个地方有一个原型,很可能在现有的 header inv_mpu.h 中。现有代码样式解决方案中最简单、最安全和最 in-keeping 的方法是添加一个“getter”访问器 counter-part mpu_get_bypass()
.
在 inv_mpu.c 中您可以添加:
unsigned char mpu_get_bypass( void )
{
return st.chip_cfg.bypass_mode ;
}
将原型声明添加到 inv_mpu.h 因此:
unsigned char mpu_get_bypass( void ) ;
然后在访问源文件中,你#include "inv_mpu.h"
,然后调用getter,例如:
if( !mpu_get_bypass() ) ...
在源文件inv_mpu.c中有一个结构定义gyro_state_s
和一个文件作用域变量声明:
static struct gyro_state_s st = {
.reg = ®,
.hw = &hw,
.test = &test
};
嵌套在这个结构中的是一个成员st.chip_cfg.bypass_mode
,我希望通过另一个文件访问它。
问题:如何在另一个文件中读取此标志 st.chip_cfg.bypass_mode
的状态?
我已经尝试了 extern struct gyro_State_s st ;
,但是当我在 if(!st.chip_cfg.bypass_mode)
中测试时仍然无法识别。
将结构放入共享 header 中,该结构包含在两个文件中。
extern 表示:'this is defined/instantiated elsewhere'
由于其下的结构不会编译为任何物理代码(结构的实例会编译,结构本身只是描述了如何创建它的实例)你只需要在两者中定义相同的结构文件,最好将结构放在共享 header 中,然后在需要结构的两个文件中包含 header。
试图暴露所有st
及其定义只是为了访问这个标志是一个糟糕的设计,应该避免。 Globals are always bad,在这种情况下,您将不必要地使 st
的所有内部结构对整个程序可见。
inv_mpu.c 已经有一个函数 mpu_set_bypass()
在使用之前被调用,所以必须在某个地方有一个原型,很可能在现有的 header inv_mpu.h 中。现有代码样式解决方案中最简单、最安全和最 in-keeping 的方法是添加一个“getter”访问器 counter-part mpu_get_bypass()
.
在 inv_mpu.c 中您可以添加:
unsigned char mpu_get_bypass( void )
{
return st.chip_cfg.bypass_mode ;
}
将原型声明添加到 inv_mpu.h 因此:
unsigned char mpu_get_bypass( void ) ;
然后在访问源文件中,你#include "inv_mpu.h"
,然后调用getter,例如:
if( !mpu_get_bypass() ) ...