Ask Your Question
0

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

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

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
0

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

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
0

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

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 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

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

Seen: 555 times

Last updated: Sep 28 '20