我在 C 中遇到一个问题,我正在尝试使用一些 getter 和 setter 在多个源文件之间共享一个变量。
我在这里用一个 getter 和一个 setter 声明我的变量 (ok_button):
变量.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include "../libhd_src/libhd.h"
int ok_button;
void set_ok_button(int value){
ok_button=value;
printf("Setting ok");
}
int get_ok_button(){
return ok_button;
}
在这里,当我按下一个按钮时,它会将变量设置为 1。(无法上传此源文件的完整代码,但我在我的日志中看到当我按下时函数 set_ok_button 被正确执行(我看到每次我按下我的按钮时 printf“设置正常”))
按钮.c
#include "../libhd_src/libhd.h"
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
void * button_back_center_short(void *arg){
set_ok_button(1);
return 0;
}
在这里,我只是用 getter 函数检查变量的值。
阅读.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include "../../libhd_src/libhd.h"
int main(int argc, char **argv){
while(1){
printf("Value %d", get_ok_button());
usleep(500000);
}
}
问题是 read.c 中显示的值始终为“0”,即使我按下按钮并将值设置为 1...
有人知道哪里出了问题吗?如果您看到更好的解决方案,请随时告诉我 :)
最佳答案
我认为你的问题可能是你在不同的文件中有多个 set_ok_button
和 get_ok_button
函数。确保只在一个文件中定义它们,并在标题中添加 2 行声明(但不定义)函数:
void set_ok_button(int value);
int get_ok_button();
关于c - C 中的 Getter 和 Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39168552/