0

I use Raspberry Pi 3 Zero, put the sudo apt-get install libi2c-dev package, compile g ++ (Raspbian 8.3.0-6 + rpi1) 8.3.0 Why am I getting these errors?

Command:

g++ -c main.cpp
g++ -c HX.cpp
g++ main.o HX.o -lm -li2c -pthread -lpigpio -lrt -lwiringPi
    HX.cpp: In constructor ‘HX::HX(int32_t)’:
    HX.cpp:34:17: error: ‘i2c_smbus_read_byte_data’ was not declared in this scope
    int8_t power = i2c_smbus_read_byte_data(device_id, MPU_POWER1);
                   ^~~~~~~~~~~~~~~~~~~~~~~~
    HX.cpp:34:17: note: suggested alternative: ‘i2c_smbus_ioctl_data’
    int8_t power = i2c_smbus_read_byte_data(device_id, MPU_POWER1);
                   ^~~~~~~~~~~~~~~~~~~~~~~~
                   i2c_smbus_ioctl_data
    HX.cpp:35:2: error: ‘i2c_smbus_write_byte_data’ was not declared in this scope
    i2c_smbus_write_byte_data(device_id, MPU_POWER1, ~(1 << 6) & power);
    ^~~~~~~~~~~~~~~~~~~~~~~~~
    HX.cpp:35:2: note: suggested alternative: ‘i2c_smbus_ioctl_data’
    i2c_smbus_write_byte_data(device_id, MPU_POWER1, ~(1 << 6) & power);
    ^~~~~~~~~~~~~~~~~~~~~~~~~
    i2c_smbus_ioctl_data

HX.cpp

#include "HX.hpp"
HX::HX(int32_t id){
    device_id = id;
    if(device_id < 0){
        fprintf(stderr, "Error number: %d\nString error: %s\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }

    if(ioctl(device_id, I2C_SLAVE, MPU_ADDRESS) < 0){
        fprintf(stderr, "Error number: %d\nString error: %s\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }

    int8_t power = i2c_smbus_read_byte_data(device_id, MPU_POWER1);
    i2c_smbus_write_byte_data(device_id, MPU_POWER1, ~(1 << 6) & power);

    fprintf(stdout, "%sMPU9250 initialize successful\n", KGRN);
}

HX::~HX(){
    close(device_id);
}
3
  • What does HX.hpp contain?
    – walnut
    Sep 7, 2019 at 19:13
  • HX.hpp contain is: ` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdint.h> #include <errno.h> #include <stdbool.h> #include <unistd.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/types.h> #include <locale.h> `
    – goose
    Sep 7, 2019 at 20:41
  • I included linux/i2c.h and linux/i2c-dev.h. But the compiler says "error: ‘i2c_smbus_read_byte_data’ was not declared in this scope"
    – goose
    Sep 7, 2019 at 20:43

1 Answer 1

2

I included few headers in HX.cpp, but I used extern "C"

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

It's working)

2
  • But, why should i use extern "C" ?
    – goose
    Sep 8, 2019 at 11:35
  • They are C headers and you need to mark them as such to use in C++.
    – r_ahlskog
    Sep 8, 2019 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.