ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
1

How to link dynamic library "-li2c" with Cmake? (undefined reference to 'i2c_smbus_read_byte_data')

asked 2020-09-14 14:17:42 -0600

Totemi1324 gravatar image

Hello,

As I'm rather new to Cmake usage, I don't really know how to solve this problem. In my C++ code, I use functions from the Linux i2c library, as follows:

extern "C" {
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>
}
#include <sys/ioctl.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>

bool cpi2c_writeRegister(uint8_t address, uint8_t subAddress, uint8_t data) {
    return i2c_smbus_write_byte_data(address, subAddress, data) == 0;
}

I usually compile with Cmake using CMakeLists, but now it doesn't work since it states: undefined reference to 'i2c_smbus_write_byte_data'. I tried with G++ to link dynamically:

g++ -std=c++11 -Wall -c main.cpp
g++ -std=c++11 -o Main main.o -li2c

This worked well and there are no problems. The problem is I really need to compile with CMakeLists, so do you know a way how to achieve this? Cmake does not find the package by default (since it has no .config-file) and I don't know where the functions from i2c/smbus.h are defined.

Thanks for your help!

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2021-05-14 23:45:17 -0600

xiahua gravatar image

Step 1: add

target_link_libraries(${PROJECT_NAME} 
  i2c
)

To your CMakeList.txt.

Step 2: Declare the headers as "C",

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

Because libi2c.so is a dynamic library compiled with gcc.

If you does not declare it explicitly, the compiler of ROS , which is g++, will generate different function names in the symbol table thus the ld command cannot find any match in the i2c library.

Referece: https://en.wikipedia.org/wiki/Name_ma...

edit flag offensive delete link more

Comments

This answer worked for me as well. Thanks @xiahua

sameh4 gravatar image sameh4  ( 2022-12-29 13:20:33 -0600 )edit
0

answered 2020-09-28 14:41:55 -0600

kmilo7204 gravatar image

Heya!!

I was facing this issue as well. You can try to add to your CMakeLists the following. As far as I know this will link the desired library to your executable.

target_link_libraries(${PROJECT_NAME} 
  i2c
)

Watch this thread for more information.

Hope it helps!!

edit flag offensive delete link more

Comments

This did not work for me. I dont know what other details to add here.

DauntingROS gravatar image DauntingROS  ( 2021-03-27 04:52:29 -0600 )edit

Question Tools

Stats

Asked: 2020-09-14 14:17:42 -0600

Seen: 2,507 times

Last updated: Sep 28 '20