如何在不使用 .h 中的 extern 的情况下访问其他文件中的静态变量?

How to access Static Variable in other file without using extern in .h?

假设文件first.c中有一个静态变量static uint8 Data_updated_u8,并且在一些循环函数中它的值正在更新。现在我想要在 second.c 文件中获取 Data_updated_u8 的更新值。 有没有办法在不使用外部变量的情况下在 second.c 中获取静态变量?或者使用指针?

Now I want the get the updated value of Data_updated_u8 in second.c file

这是一个设计问题。如果您在 .c 文件的文件范围内声明了一个局部 static 变量,那么该变量将被视为私有变量。如果您的设计合理,其他文件应该不需要直接访问该变量。因此,这是您应该退后一步并首先考虑您的程序设计的地方。

Or using pointers?

坏主意,这比使用全局变量还要糟糕。您不应该通过指针公开私有变量。您也不应该使用全局变量。总的来说,您不应该通过创建像这样的奇怪依赖关系来设计多个文件之间的紧耦合

如果您确实需要与其他文件共享此变量,那么正确的方法是编写一个 setter/getter API 函数,您通过头文件。然后 set/get 按值计算数据。 (你可能甚至不需要从外面设置它?)

此外,不要发明一些当地的车库标准 uint8。使用来自stdint.h.

的国际C语言标准uint8_t

data.h

#include <stdint.h>

uint8_t get_data (void);

void set_data (uint8_t val);

data.c

#include "data.h"

static uint8_t data;

uint8_t get_data (void) { return data; }

void set_data (uint8_t val) { data = val; }