Search code examples
c++ccmakecmake-custom-command

Alternatives for CMake commands


I am new to CMake and was going through the CMake documentations and tutorials. I was able to understand that the target_include_directories command is just the -I option for the compiler (gcc for me). I tried doing it adding the directories manually by using set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I <Path>") and it worked perfectly fine!!

My CMakeLists.txt looks something like this:

cmake_minimum_required(VERSION 3.6)
  
project(Project VERSION 1.0 DESCRIPTION "C Project" LANGUAGES C)
 
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I <path-to-header>")

add_library(basic file1.c file2.c)

#target_include_directories(basic PUBLIC "path-to-header") 
#target_include_directories() is commented out as CMAKE_C_FLAGS have been set

add_executable(main.out main.c)

target_link_libraries(main.out PRIVATE basic)

I wanted to know if there any similar and alternative for the target_link_libraries command using which we can pass -L and -l options to linker in CMake??


Solution

  • To answer your question literally: There is the variable CMAKE_EXE_LINKER_FLAGS and its specializations CMAKE_EXE_LINKER_FLAGS_<CONFIG> for certain configurations like RELEASE or DEBUG or whatever configurations you might have defined. See the CMake documentation for more.

    BUT, I highly disrecommend to use these unless you need to pass a very special compiler/linker option CMake does not know about, because these are specific to your compiler.

    The point of using CMake is to describe the build process independent of the concrete compiler and platform, such that you can easily switch to another one or at least update your compiler without having to refactor your build code. So, better stick with the generic target_include_directories, target_link_libraries, and similar commands as much as possible.

    If you really have to use CMAKE_C_FLAGS or CMAKE_EXE_LINKER_FLAGS I'd recommend to wrap them into an if clause making sure that you are building with the expected compiler on the expected platform and put a fatal error message into the else clause to make future users aware of a possible problem.