How to link dynamic library "-li2c" with Cmake? (undefined reference to 'i2c_smbus_read_byte_data')
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!
Asked by Totemi1324 on 2020-09-14 14:17:42 UTC
Answers
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!!
Asked by kmilo7204 on 2020-09-28 14:41:55 UTC
Comments
This did not work for me. I dont know what other details to add here.
Asked by DauntingROS on 2021-03-27 04:52:29 UTC
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_mangling
Asked by xiahua on 2021-05-14 23:45:17 UTC
Comments
This answer worked for me as well. Thanks @xiahua
Asked by sameh4 on 2022-12-29 14:20:33 UTC
Comments