简体   繁体   中英

Qt Creator cannot find library with custom cmake step

In Qt Creator (version 3.0.1, with Qt version 5.2.1), I have made a custom cmake step (instead of qmake ), with the following CMakeLists.txt file:

cmake_minimum_required (VERSION 2.8)

add_executable (myapp source.cpp)

target_link_libraries(myapp dl)

In my source.cpp file, I have the following code:

#include <dlfcn.h>

int main()
{
    dlopen("mylibrary.so", RTLD_NOW|RTLD_GLOBAL);
    return 0;
}

And mylibrary.so is located in /usr/lib .

When I compile this using cmake and make from the command line, it compiles as expected. However, if I try to build this in Qt Creator, I receive the following error:

undefined reference to `dlopen'

This suggests that Qt Creator does not know where to look to find libdl.so , which is in /usr/lib/x86_64-linux-gnu .

So my question is: Why does running cmake and make from the command line work, whereas building in Qt Creator does not work? And how do I tell Qt Creator where to search for libdl.so ?

First of all, you should use QLibrary in Qt software for dealing with dynamic loading, lookup and the like. You would also spare the hassle that you are seeing now.

Secondly, you can use this, but it is a bit hard-wiring things, admittedly:

target_link_libraries(myapp /usr/lib/x86_64-linux-gnu/libdl.so)

Thirdly, the even better approach would be to use some find module for this as follows:

# - Find libdl
# Find the native LIBDL includes and library
#
# LIBDL_INCLUDE_DIR - where to find dlfcn.h, etc.
# LIBDL_LIBRARIES - List of libraries when using libdl.
# LIBDL_FOUND - True if libdl found.
IF (LIBDL_INCLUDE_DIR)
# Already in cache, be silent
SET(LIBDL_FIND_QUIETLY TRUE)
ENDIF (LIBDL_INCLUDE_DIR)
FIND_PATH(LIBDL_INCLUDE_DIR dlfcn.h)
SET(LIBDL_NAMES dl libdl ltdl libltdl)
FIND_LIBRARY(LIBDL_LIBRARY NAMES ${LIBDL_NAMES} )
# handle the QUIETLY and REQUIRED arguments and set LIBDL_FOUND to TRUE if
# all listed variables are TRUE
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibDL DEFAULT_MSG LIBDL_LIBRARY LIBDL_INCLUDE_DIR)
IF(LIBDL_FOUND)
SET( LIBDL_LIBRARIES ${LIBDL_LIBRARY} )
ELSE(LIBDL_FOUND)
SET( LIBDL_LIBRARIES )
ENDIF(LIBDL_FOUND)
MARK_AS_ADVANCED( LIBDL_LIBRARY LIBDL_INCLUDE_DIR )

and then you can find it as follows given that you have it in your cmake module path:

find_package(LIBDL REQUIRED)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM