【问题标题】:Joystick Code error of undeclared variables未声明变量的操纵杆代码错误
【发布时间】:2014-02-25 20:21:59
【问题描述】:

我正在尝试编写代码来读取操纵杆轴值,我最终希望能够使用这些值来控制电机。在大量尝试弄清楚 C 以及如何使用操纵杆 api 之后,我编写了这段代码。一开始它只有一个变量未声明的错误,然后当我改进代码,使其更具可读性和更容易理解时,当我去编译它时,我得到了另一个相同的错误,希望第一个会有走了! 这是我的代码(请原谅评论):

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <linux/joystick.h> /* lots of included headers because */ 
                            /*  I wasn't sure which I needed!   */

#define JS_EVENT_AXIS           0x02    /* joystick moved */

int open_joystick() {

    int fd;                             /* fd declared I thought */
        fd = open ("/dev/js0", O_RDONLY | O_NONBLOCK);

    return fd;                          /* code likes something to return */
}

int read_joystick_thrust_axis(struct js_event js) /* declare r_j_t_a variable and the js instance */


    while (1) {                                          /* loop forever */
        while (read (fd, &js, sizeof(js)) > 0) {         /* while there is an event */
          if (js_event.type == JS_EVENT_AXIS) {          /* and if that is an axis event */
            if (js_event.number == 1) {                  /* and if that event is on the right axis */  
               printf ("Joystick at %8hb\n", js.value);  /* print that instance of the joysticks value */
                                        }
                                    }
                                }
                            }
    return 0; }            /* keeping C happy by returning something */

我从 gcc 得到的错误是:

pi@raspberrypi ~/rc $ gcc joystick.c
joystick.c: In function ‘read_joystick_thrust_axis’:
joystick.c:24:16: error: ‘fd’ undeclared (first use in this function)
joystick.c:24:16: note: each undeclared identifier is reported only once for each function it appears in
joystick.c:25:8: error: ‘js_event’ undeclared (first use in this function)

有人能解释一下为什么我会收到这些错误并提出修复建议吗? 提前谢谢你。

【问题讨论】:

  • fdopen_joystick 中声明,其词法范围是open_joystick 的范围。

标签: c linux compiler-errors joystick


【解决方案1】:

open_joystick 设置fd,但fdopen_joystick 的本地对象,因此read_joystick_thrust_axis 无法读取。将read_joystick_thrust_axis转换为允许fd作为参数传递,并传递open_joystick的返回值,像这样:

变化:

int read_joystick_thrust_axis(struct js_event js)

int read_joystick_thrust_axis(int fd, struct js_event js)

然后当你调用它时(来自main 或其他),做

int fd;
fd = open_joystick();
...
int read_joystick_thrust_access (fd, whatever);

关于js_event 错误,变量名为js,类型为struct js_event。因此,您要引用 js.type 而不是 js_event.type

【讨论】:

  • 非常感谢现在更有意义了!我将如何转换“read_joystick_thrust _axis”以允许“fd”作为参数传递?而且我不确定我是否理解您与您谈论的有关“传递'open_joystick'的返回值”的内容/位置,您可以尝试重新解释一下吗?对不起,这里有点新手。
  • 我已经修改了答案。
  • 谢谢,好的,我想我现在明白了!所以只有当我想从另一个函数调用它时,我才会使用从 main 调用它的一点点?对不起
  • 你必须从另一个函数调用它,否则它不会被调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多