I'm getting the error undefined reference to
i2c_smbus_read_word_data(int, unsigned char)`
I've tried wrapping a few of my libraries in extern "C"
but I get the same error. I tried this after seeing this answer to a similar problem.
Regardless of whether I wrap some or all of these include #include <linux/i2c-dev.h>, #include <i2c/smbus.h>, #include <linux/i2c.h>, #include <sys/ioctl.h>
statements I get the same error.
The error is i2c_read.cpp:(.text+0xf8): undefined reference to
i2c_smbus_read_word_data(int, unsigned char)'
collect2: error: ld returned 1 exit status`
I am running my command $g++ i2c_read.cpp -li2c
with -li2c
as you can see.
extern "C" {
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>
}
#include <linux/i2c.h>
#include <sys/ioctl.h>
#include <fcntl.h> /* For O_RDWR */
#include <unistd.h>
#include <iostream>
using namespace std;
int file;
int adapter_nr = 2;
char filename[20];
int main() {
cout << filename << 19 << "/dev/i2c-1" << adapter_nr;
file = open(filename, O_RDWR);
if (file < 0) {
exit(1);
}
int addr = 0x74;
if (ioctl(file, I2C_SLAVE, addr) < 0) {
exit(1);
}
__u8 reg = 0x40;
__s32 res;
char buf[10];
res = i2c_smbus_read_word_data(file, reg);
if (res < 0) {
/* ERROR HANDLING: i2c transaction failed */
} else {
/* res contains the read word */
}
buf[0] = reg;
buf[1] = 0x42;
buf[2] = 0x43;
if (write(file, buf, 3) != 3) {
/* ERROR HANDLING: i2c transaction failed */
}
}
I did a sudo apt-get update and the problem went away.
I also ran a few commands to update the compiler, though it still says my g++ version is 7.5, so that might have also contributed.