5

I am using CMake under Ubuntu 14.04 to configure my project. I need to use a 3rd party library (say stuff.so). In the CMakeLists.txt, I use TARGET_LINK_LIBRARIES to link the stuff library. However, I got an error:

DIR_TO_LIB/stuff.so:-1: error: undefined reference to `shm_open'

I tried to put these flag in the CMakeLists.txt but it didn't work:

set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lrt")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lrt")

A post (link) saying that -lrt should be put as the last argument of g++. In my case where CMake is used, how shall I do this?

UPDATE: I added

SET (CMAKE_VERBOSE_MAKEFILE 1)

and I found that -lrt is not the last (even though I put it at the end of the target link). Please see this link for compile output.

As you can see from the compile output, there are some linking flags for the opencv. I don't understand how could this happen as I link the OpenCV library first in the TARGET_LINK_LIBRARIES. How does CMake handle these linking order?

Please also see my CMakeLists.txt.

Thank you.

Community
  • 1
  • 1
linzhang.robot
  • 359
  • 1
  • 8
  • 23

2 Answers2

6

You need to add rt in TARGET_LINK_LIBRARIES as a last one, for example:

TARGET_LINK_LIBRARIES(my_app ${Boost_LIBRARIES} rt)

You can verify position of rt by enabling verbose build output:

SET (CMAKE_VERBOSE_MAKEFILE 1)
doqtor
  • 8,414
  • 2
  • 20
  • 36
  • Thank you for your answer. I tried your solution but it didn't work. Please see my update for the compile output and my CMakeLists. Thanks very much – linzhang.robot Jul 01 '15 at 09:11
  • hmm some of OpenCV libs are linked twice. Try adding `ADD_DEPENDENCIES(vidcapture ${OpenCV_LIBS} Qt5::Widgets Qt5::Multimedia aja ajastuff rt)` between `ADD_EXECUTABLE` and `TARGET_LINK_LIBRARIES` – doqtor Jul 01 '15 at 09:28
  • Yes the issue is that the opencv was link twice. When I removed opencv from the `target_link_libraryies` it could pass the compile. I also tried the `ADD_DEPENDENCIES` but the same error. – linzhang.robot Jul 01 '15 at 09:36
1

First, the answer is: Append -lrt to the end of your macro target_link_libraries for your target my_app, i.e.,

target_link_libraries(my_app ${Boost_LIBRARIES} -lrt)

That achieves the same effect in solving the missing library to be linked against by using e.g. gcc compiler:

gcc my_app.c -o my_app -lrt

The reason behind, as you may have already figured out, is the missing required ("realtime") library. For that, you can check by typing in the command

man shm_open

and then finding the key snippet explaining the reason of adding -lrt, i.e., "These functions are provided in glibc 2.2 and later. Programs using these functions must specify the -lrt flag to cc in order to link against the required ("realtime") library."

lenard_xu
  • 31
  • 1
  • 2