Search code examples
c++linuxwindowscmakecmake-gui

cmake: How to write CMakeLists.txt in order to facilitate the transplant on Linux programs to Windows?


I wrote the CMakeLists.txt file with the following file structure on Linux

-main
--include
--bin
--lib
----SRC
------CMakeLists.txt
------dir1
--------CMakeLists.txt
------dir2
--------CMakeLists.txt

dir1/CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
set(HOME "/workspace/main")
set(INCLUDE "${HOME}/include")
set(LIB "${HOME}/lib")
set(LIBRARY_OUTPUT_PATH "${HOME}/lib")
set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_COMPILER "g++")
set(CMAKE_C_FLAGS_DEBUG "xxx")
set(CMAKE_CXX_FLAGS_DEBUG "xxx")
include_directories(${INCLUDE} ${INCLUDE}/AR ${INCLUDE}/linux-x86_64)
add_library(video STATIC video.c video2.c)

dir2 directory CMakeLists.txt similar content

SRC/CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
add_subdirectory(dir1)
add_subdirectory(dir2)

My question is: How to write CMakeLists.txt in order to facilitate the transplant on Linux programs to Windows?


Solution

  • Variable CMAKE_SOURCE_DIR refers to the top level project directory. Use this variable instead of HOME for refer to directories in your project.

    Alternatively, for being able to build subprojects as standalone projects, you may use PROJECT_SOURCE_DIR for refer to directory of the current project. Note, that you need to have project() in CMakeLists.txt for such subprojects (otherwise most of CMake commands will not work).

    lib/SRC/dir1/CMakeLists.txt:

    cmake_minimum_required(VERSION 2.8)
    project(dir1)
    set(HOME "${PROJECT_SOURCE_DIR}/../../..")
    ...
    

    Also, there is variable CMAKE_CURRENT_SOURCE_DIR which always refers to current source directory (which CMakeLists.txt is executed).

    lib/SRC/dir1/CMakeLists.txt:

    ...
    set(HOME "${CMAKE_CURRENT_SOURCE_DIR}/../../..")
    ...