Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: What is the difference between `include_directories` versus `target_link_libraries`

Tags:

c++

cmake

I am building a moderately sized C++ library and have cobbled together my CMakeLists.txt file from a bunch of different examples, etc. I was trying to understand the difference between include_directories versus the target_link_libraries instructions.

I list some of my code below, but just wanted to preface with a comment. I use the Boost library to build some of my code. So I have an instruction to INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS}) to include the Boost source directories in the build process. So I assume that Cmake will include these Boost Source files when building any executable--without any additional explicit instruction.

But later I have a TARGET_LINK_LIBRARIES( gd_validator ${Boost_LIBRARIES} ) when building an executable. So that suggests that I need to not only include the Boost directory, but then also explicitly link it with the executable.

So I was not sure if I actually needed both steps, or if I just needed the INCLUDE_DIRECTORIES instruction and that was it.

cmake_minimum_required(VERSION 3.7)
project(XXX) 
find_package(Boost 1.58.0 REQUIRED COMPONENTS system filesystem program_options chrono timer date_time REQUIRED)
if(NOT Boost_FOUND)
    message(FATAL_ERROR "NOTICE: This demo requires Boost and will not be compiled.")
endif()
set(Boost_USE_STATIC_LIBS        ON)
set(Boost_USE_MULTITHREADED      ON)
set(Boost_USE_STATIC_RUNTIME    OFF)

INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS})
LINK_DIRECTORIES(${Boost_LIBRARY_DIRS})

file(GLOB lib_SRC RELATIVE "lib/" "*.h" "*.cpp")
file(GLOB test_SRC RELATIVE "tests/" "*.h" "*.cpp")

# need to fix the instruction below to reference library
set(SOURCE_FILES ${lib_SRC} tests/testComplexCreator.cpp tests/testDataFormatter.cpp tests/testComplexAnalysis.cpp tests/testFascadeClass.cpp)
add_library(libXXX SHARED ${SOURCE_FILES})    
add_executable(${PROJECT_NAME} main.cpp random_mat_vector_generator.h random_mat_vector_generator.cpp)
add_executable(gd_validator gudhi_validator.cpp)
TARGET_LINK_LIBRARIES( gd_validator ${Boost_LIBRARIES} )
like image 881
krishnab Avatar asked Jan 04 '23 04:01

krishnab


1 Answers

Yes, you need both.

include_directories will tell to the compiler where to look for the header files, in this case, the header files for the boost library.

target_link_libraries will tell to the linker which libraries you want to link against your executable.

While headers will provide (most of the time) just the interface to access the library, the library itself is precompiled and linked to your application.

like image 158
Natanael Ramos Avatar answered Jan 11 '23 23:01

Natanael Ramos