Search code examples
cmakelibspotifyclion

Linking against external library with CMake


I'm currently at a bit of a loss when trying to use the Libspotify SDK in my CMake project.

CMakeLists.txt:

cmake_minimum_required(VERSION 3.2)
project(spotti)

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/modules/")

find_package(Spotify REQUIRED)
include_directories(${Spotify_INCLUDE_DIR})
set(LIBS ${LIBS} ${Spotify_LIBRARIES})

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread")

set(SOURCE_FILES main.cpp)
add_executable(spotti ${SOURCE_FILES})

FindSpotify.cmake:

# - Find Spotify
# Find the native Google Sparse Hash Etc includes
#
#  Spotify_INCLUDE_DIR - where to find sparse_hash_set, etc.
#  Spotify_FOUND       - True if Spotify found.


if (Spotify_INCLUDE_DIR)
    # Already in cache, be silent
    set(Spotify_FIND_QUIETLY TRUE)
endif ()

find_path(Spotify_INCLUDE_DIR api.h PATHS
    /opt/local/include/libspotify
    /usr/local/include/libspotify
    /usr/include/libspotify
    /home/denvercoder21/Development/cpp/spotti/libspotify/include/libspotify/
    )

set(Spotify_LIB_PATHS /usr/local/lib /opt/local/lib /home/denvercoder21/Development/cpp/spotti/libspotify/lib/)
find_library(Spotify_LIB NAMES spotify PATHS ${Spotify_LIB_PATHS})

if (Spotify_INCLUDE_DIR AND Spotify_LIB)
    set(Spotify_FOUND TRUE)
else ()
    set(Spotify_FOUND FALSE)
endif ()

if (Spotify_FOUND)
    if (NOT Spotify_FIND_QUIETLY)
        message(STATUS "Found Spotify: ${Spotify_INCLUDE_DIR}")
    endif ()
else ()
    message(STATUS "Not Found Spotify: ${Spotify_INCLUDE_DIR}")
    if (Spotify_FIND_REQUIRED)
        message(FATAL_ERROR "Could NOT find Spotify includes")
    endif ()
endif ()


mark_as_advanced(
    Spotify_LIB
    Spotify_INCLUDE_DIR
    )

My libspotify folder is in the project root directory. I think I might be missing a target_link_libraries() in my CMakeLists.txt. Or not? Anyway, CMake runs without errors with these files, but compiling my project gives me undefined reference errors. What's wrong?


Solution

  • I think I might be missing a target_link_libraries() in my CMakeLists.txt.

    Yes, you should explicitly link with Spotify:

    target_link_libraries(spotti Spotify)
    

    find_package() does not perform automatic linking.