c - C 中的 Getter 和 Setter

标签 c memory setter getter

我在 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_buttonget_ok_button 函数。确保只在一个文件中定义它们,并在标题中添加 2 行声明(但不定义)函数:

void set_ok_button(int value);
int get_ok_button();

关于c - C 中的 Getter 和 Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39168552/

相关文章:

在 C 中复制链表

c - 由 C 代码制作的 mex 在循环中崩溃,但运行一次时不会崩溃

java - 如何修改 Eclipse 自动生成的设置方法签名?

java - 如何累积一个调用 setter 方法并以其中的变量作为参数?

c++ - 类成员变量的setter怎么写?

c - 为什么这个 malloc 会在我的虚拟机上导致段错误?

c - 在 Windows 中找不到 libxml/xmlversion.h 文件

c - 使用结构和数组的 Strcmp 的 If 语句不起作用

Python, GTK, Webkit & scraping, 大内存问题

GIT 从内存提交,而不是文件