cmaketarget-link-libraries

cmake target_link_libraries(), when should we use?


I am new to CMake and just want to understand some details about how target_link_libraries works.

To include a library, let's say boost. We can simply do include_directories(BOOST_LIBRARY_PATH). This allows my project to compile correctly and no errors report.

But after reading some posts online, I notice that people usually add target_link_libraries(executable boost_library) after include directories, so I just wonder why this line is needed.

Since my project is quite sensitive in terms of performance (i.e., I want it to run as fast as possible) my questions are as follows:

(1) What target_link_libraries actually do? (2) If we don't add this line, does it hurt performance? (3) What are the advantages of including target_link_libraries?


Solution

  • target_link_libraries does different things depending on the parameter passed. If you should use it or not depends on what exactly you're trying to achieve. (I'd recommend using target_include_directories instead of include_directories though, since it limits the use of the include dir to a single target and also allows you to make include dirs available to linking cmake library targets, if the headers are used in public headers of a library target.)

    My recommendation in your case would be:

    find_package(Boost REQUIRED COMPONENTS headers CONFIG PATHS "/your/boost/install/path")
    target_link_libraries(executable PRIVATE Boost::headers)
    

    Note that the program won't be any faster of slower compared to using include_directories to specify the input directory; the speed of the cmake configuration may change a bit, but I don't recommend cutting any corners there.