0
root +-- main.cpp +-- CMakeLists.txt +-- liblib1.a 

CMakeLists.txt:

cmake_minimum_required(VERSION 3.5) project(testlib LANGUAGES CXX) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_executable(testlib main.cpp) target_link_libraries(testlib ${CMAKE_SOURCE_DIR}/liblib1.a ) 

How to link without ${CMAKE_SOURCE_DIR} like:

target_link_libraries(testlib lib1 ) 

How to make ${CMAKE_SOURCE_DIR} path visible to CMAKE ld?


BTW, below didn't work error: cannot find -llib1

link_directories(${CMAKE_SOURCE_DIR}) target_link_libraries(testlib lib1 ) 
2
  • You can copy the library into your system library path. Commented Mar 17, 2020 at 1:19
  • @squareskittles Is possible to add the ${CMAKE_SOURCE_DIR} make it the same as system library path? Commented Mar 17, 2020 at 1:41

2 Answers 2

2

Use target_link_directories:

Specify the paths in which the linker should search for libraries when linking a given target.

...

NOTE: This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked.

target_link_directories(testlib PUBLIC ${CMAKE_SOURCE_DIR}) 
Sign up to request clarification or add additional context in comments.

3 Comments

this did work...but I just want to make the certain path be visible to ld
I do not understand you. How does this not make the path visible to the linker? You want to just add the path to /etc/ld.so.conf? Use LD_PRELOAD?
target_link_directories(testlib PUBLIC ${CMAKE_SOURCE_DIR}) will automatically find the libs, but I want only ${CMAKE_SOURCE_DIR} visible to the linker, then I specific the link libs manually not automatically.
0

To specify the directory of lib in CMake is link_directories.

I didn't get works because link_directories have to put in front of add_executable.

like this:

link_directories(${CMAKE_SOURCE_DIR}) add_executable(testlib main.cpp) target_link_libraries(testlib lib1 ) 

BTW, I found a great tutorial talks about this kind of CMake dependency usage. https://pabloariasal.github.io/2018/02/19/its-time-to-do-cmake-right/

2 Comments

Use of the link_directories() command is not recommended, it even says in the documentation. You should prefer the target-based commands, as used in KamilCuk's answer.
@squareskittles Yes, I understand, I actually using the lib with the specific path, this question just because of curiosity. Thanks for reminding me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.