Philipp Ludwig
Philipp Ludwig

Reputation: 4190

Avoid automatically added "lib" prefix when using target_link_libraries

I'm trying to link a C++ project to the RCpp library; the file is called Rcpp.so, not the linux-default libRcpp.so. Furthermore, the library resides at the non-standard location /usr/lib/R/site-library/Rcpp/libs.

So I tried using a combination of find_library and target_link_libraries:

cmake_minimum_required(VERSION 3.8)
project("R-Tests")

find_library(RCPP
    NAMES Rcpp.so
    HINTS /usr/lib/R/site-library/Rcpp/libs
)
if (NOT RCPP)
    message(FATAL_ERROR "Could not find Rcpp - exiting.")
else()
    message("Found Rcpp: " ${RCPP})
endif()

# test target
add_executable(rcpptest main.cpp)
target_link_libraries(rcpptest ${RCPP})

Configuring works fine, CMake outputs:

Found Rcpp: /usr/lib/R/site-library/Rcpp/libs/Rcpp.so

However, during build, CMake passes -lRcpp to the compiler, which causes the compilation to fail, since the library file is not named libRcpp.so but instead Rcpp.so:

[100%] Linking CXX executable rcpptest
/usr/bin/cmake -E cmake_link_script CMakeFiles/rcpptest.dir/link.txt --verbose=1
c++     CMakeFiles/rcpptest.dir/main.cpp.o  -o rcpptest  -L/usr/lib/R/site-library/Rcpp/libs -Wl,-rpath,/usr/lib/R/site-library/Rcpp/libs -lRcpp
/usr/bin/ld: cannot find -lRcpp
collect2: error: ld returned 1 exit status

Since the message line prints the full path to the Rcpp.so file just fine, is there any way to let target_link_libraries just add this path to the compiler instead of a combination of -L and -l?

According to this question, this should be disabled by adding cmake_policy(SET CMP0060 NEW); however, I can't see any change in the behavior of CMake if I set this to NEW or OLD.

Upvotes: 4

Views: 2929

Answers (1)

Botje
Botje

Reputation: 30807

You may have been bitten by the OLD (default) behavior of CMP0060, which converts absolute paths back to -lfoo.

Alternatively, define and use an IMPORTED target:

add_library(Rcpp SHARED IMPORTED)
set_property(TARGET Rcpp PROPERTY IMPORTED_LOCATION /usr/lib/R/site-library/Rcpp/libs/Rcpp.so)
target_link_libraries(rcpptest Rcpp)

Upvotes: 5

Related Questions