【问题标题】:Can't compile i2c_smbus_write_byte on Raspberry Pi 4无法在 Raspberry Pi 4 上编译 i2c_smbus_write_byte
【发布时间】:2020-05-07 12:23:17
【问题描述】:

有人试过在树莓派 4 上使用 i2c_smbus_write_byte 或任何类似功能吗?

我无法让它编译它在链接时失败并且找不到它。 我按照这里的描述使用它:http://synfare.com/599N105E/hwdocs/rpi/rpii2c.html

所有推荐的头文件都在那里,而且 Makefile 中还有 -li2c

谁能说出问题所在?我目前不知道

【问题讨论】:

    标签: c compilation i2c raspberry-pi4 smbus


    【解决方案1】:

    可能值得检查一下您的系统上是否存在 libi2c-dev。

    sudo apt-get install libi2c-dev

    可能就是你所需要的。

    【讨论】:

    • 感谢您的快速回复,但这是我检查的第一件事。 Buster 现在使用此软件包的第 4 版。版本 3 包含 i2c-dev.h 中的所有 smbus 函数。所以你只需要包括这个。但现在不行了,理论上你必须现在添加 -li2c 才能使用这些功能,但它似乎不起作用。我检查了一下,这些功能肯定从 i2c-dev.h 中消失了。但是,即使使用 -li2c 也找不到它们,那么它们在哪里呢?
    【解决方案2】:

    你链接的页面说:

    对于 Buster 版本,截至 2019 年 6 月,必要的详细信息 使用 i2c_smbus_write_byte_data() 和兄弟姐妹,需要以下 包含语句:

    #include <unistd.h>
    #include <fcntl.h>
    #include <sys/ioctl.h>
    #include <linux/i2c-dev.h>
    #include <i2c/smbus.h>
    

    使用 fgrep 可以确认函数在 /usr/include/i2c/smbus.h 中声明:

    # cd /usr/include; fgrep -R i2c_smbus_write_byte *
    i2c/smbus.h:extern __s32 i2c_smbus_write_byte(int file, __u8 value);
    i2c/smbus.h:extern __s32 i2c_smbus_write_byte_data(int file, __u8 command, __u8 value);
    

    所以这应该有效:

    #include <unistd.h>
    #include <fcntl.h>
    #include <sys/ioctl.h>
    #include <linux/i2c-dev.h>
    #include <i2c/smbus.h>
    
    int main(void) {
      int i2c = open("/dev/i2c-1", O_RDWR);
      i2c_smbus_write_byte(i2c, 1);
      close(i2c);
      return 0;
    }
    

    我测试这个例子在最新的 Raspbian Buster Lite 中编译成功:

    gcc test.c -otest -li2c
    

    如果你使用的是 g++ 而不是 gcc,那么你应该用 extern "C" 包装 include 指令:

    extern "C" {
      #include <linux/i2c-dev.h>
      #include <i2c/smbus.h>
    }
    

    【讨论】:

    • 我试过你的代码,但没有为我编译。它屈服于相同的“未定义引用”错误。虽然有 2 个不同,但我使用的是 Buster 桌面,而不是 gcc,而是 g++ (4.9)。
    • 好像来自g++。我再次尝试了您的代码,它可以用 gcc 编译,但不能用 g++4.9 编译。我必须调查这个方向。感谢您的帮助。
    • 使用 g++ 你应该用 extern "C" {} 包装包含指令。我更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 2020-11-16
    • 2021-03-20
    • 2023-03-08
    • 1970-01-01
    • 2022-08-22
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多