Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a library path in cmake?

Tags:

c++

cmake

I have 2 folders "inc" and "lib" in my project which have headers and static libs respectively. How do I tell cmake to use those 2 directories for include and linking respectively?

like image 247
grasevski Avatar asked Feb 19 '15 01:02

grasevski


People also ask

How do I specify a path in CMake?

CMake will use whatever path the running CMake executable is in. Furthermore, it may get confused if you switch paths between runs without clearing the cache. So what you have to do is simply instead of running cmake <path_to_src> from the command line, run ~/usr/cmake-path/bin/cmake <path_to_src> .

Where is my CMake library?

A short-hand signature is: find_library (<VAR> name1 [path1 path2 ...]) This command is used to find a library. A cache entry, or a normal variable if NO_CACHE is specified, named by <VAR> is created to store the result of this command.


2 Answers

The simplest way of doing this would be to add

include_directories(${CMAKE_SOURCE_DIR}/inc) link_directories(${CMAKE_SOURCE_DIR}/lib)  add_executable(foo ${FOO_SRCS}) target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib 

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED set_target_properties(bar PROPERTIES   IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"   INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar" )  set(FOO_SRCS "foo.cpp") add_executable(foo ${FOO_SRCS}) target_link_libraries(foo bar) # also adds the required include path 

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

like image 144
ar31 Avatar answered Sep 22 '22 06:09

ar31


might fail working with link_directories, then add each static library like following:

target_link_libraries(foo /path_to_static_library/libbar.a) 
like image 26
Oleg Kokorin Avatar answered Sep 22 '22 06:09

Oleg Kokorin