Search code examples
c++linuxi2csmbus

undefined reference to `i2c_smbus_read_block_data(int, unsigned char, unsigned char*)'


I'm trying to read a block of data from an imu (mpu9250) but when building with g++ mpu.cpp -o mpu i get the following error:

/tmp/cckh5V8w.o: In function 'imu::read_accel()': 
mpu_mine9250.cpp:(.text._ZN3imu10read_accelEv[_ZN3imu10read_accelEv]+0x94): undefined reference to 'i2c_smbus_read_block_data(int, unsigned char, unsigned char*)'
collect2: error: ld returned 1 exit status ```
int addr = 0x68;
int mpu_file;
char mpu_filename[250];
snprintf(mpu_filename, 250, "/dev/i2c-0");
if (ioctl(mpu_file, I2C_SLAVE, addr) < 0){
     exit(1);
}
__u8 buf[14];
__u8 reg = 0x3B;
int ans= i2c_smbus_read_block_data(mpu_file, reg, buf);

To include the libraries I've tried:

#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>

and also:

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

I've installed the libi2c-dev, libi2c0 and i2c-tools packages.

When using write(mpu_file, buf, 2) or read(mpu_file, buf, 1)it does work.

Thanks in advance!


Solution

  • The solutions was:

    1. Using extern C: I was using extern C, but included them in the regular way as well and that caused the problem.

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

    2. Linking libraries when building:

    g++ -o mpu mpu_mine9250.cpp -li2c