gpt4 book ai didi

c - 嵌入式 C 利用复杂结构中的标志

转载 作者:行者123 更新时间:2023-11-30 19:52:58 25 4
gpt4 key购买 nike

在源文件中inv_mpu.c有一个结构体定义gyro_state_s和一个文件范围变量声明:

static struct gyro_state_s st = {
.reg = &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) 中测试它时,它仍然无法识别。

最佳答案

仅仅为了访问这个标志而尝试公开所有 st 及其定义是一种糟糕的设计,应该避免。 Globals are always bad ,在这种情况下,您将不必要地使 st 的所有内部结构对整个程序可见。

inv_mpu.c 已经有一个函数 mpu_set_bypass() ,该函数在使用之前被调用,因此必须在某个地方有一个原型(prototype),很可能在现有头文件 inv_mpu.h 中。最简单、最安全且最符合现有代码风格的解决方案是添加一个“getter”访问器对应部分 mpu_get_bypass()

在 inv_mpu.c 中,您可以添加:

unsigned char mpu_get_bypass( void )
{
return st.chip_cfg.bypass_mode ;
}

将原型(prototype)声明添加到 inv_mpu.h 中:

unsigned char mpu_get_bypass( void ) ;

然后在访问源文件中,#include "inv_mpu.h",然后调用 getter,例如:

if( !mpu_get_bypass() ) ...

关于c - 嵌入式 C 利用复杂结构中的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51289325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com