我的脚本有一个异步对话,它轮询队列以获取新消息,同时用户执行其他任务。我已经将 web_reg_async_attributes() 放入 init,我的回调在 asyncallbacks.c 中,我的主要逻辑在 action.c 中 异步每 5 秒轮询一次,检查消息队列。当有消息时,我希望回调设置 action.c 有权访问的标志,以便它可以有条件地执行逻辑。我试过使用在 init 中声明的全局变量,但它在 asyncallbacks.c 中不可见。
有没有办法做到这一点? (我不想使用文件,因为我正在测量不到一秒的事件,如果我将文件系统放入图片中,我的响应时间将不具有代表性)。
最佳答案
在第一个文件(asyncallbacks.h
)中:
// Explicit definition, this actually allocates
// as well as describing
int Global_Variable;
// Function prototype (declaration), assumes
// defined elsewhere, normally from include file.
void SomeFunction(void);
int main(void) {
Global_Variable = 1;
SomeFunction();
return 0;
}
在第二个文件(action.c
)中:
// Implicit declaration, this only describes and
// assumes allocated elsewhere, normally from include
extern int Global_Variable;
// Function header (definition)
void SomeFunction(void) {
++Global_Variable;
}
在此示例中,变量 Global_Variable 在 asyncallbacks.h
中定义。为了在 action.h
中使用同一个变量,必须对其进行声明。不管有多少个文件,一个全局变量只定义一次;但是,它必须在包含定义的文件之外的任何文件中声明。
关于c - 如何在 async callbacks.c 和 action.c 之间共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54702359/