Search code examples
c++cmakemultiplatform

How to construct CMake files to be OS generic but specific too?


Actually, my project has this files:

/ cmake / CMakeLists.txt
/ sources / {my cpp headers ...}

And I construct the "project" (makefile or .sln...) the same way under every OS, at the root of this repository with the command:

cmake ./cmake/

But it needs some optional settings like the CMAKE_CXX_FLAGS different on each OS.

And I have chosen to put this variables in a /cmake/CMakeCache.txt but to not commit this file (since it is different between OSs). The dev has to generate (edit) this file on each machine. I only gave some instructions in a readme about this CMakeCache file.

How could I make cmake files generic again, but have this differences in a commited content too?


Solution

  • Use code like this in your CMakeLists.txt:

    if(UNIX AND NOT APPLE)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")
        set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread")
    elseif(WIN32)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DWIN32_LEAN_AND_MEAN")
    endif()
    

    Notes:

    • Append your options to ${CMAKE_CXX_FLAGS} so that user-specified settings are also included.
    • You cannot use list(APPEND ...) with compiler flags because it uses semicolons to separate parameters (this is why the code above uses set(...) with quotes)
    • APPLE is also UNIX, so we need NOT APPLE when we actually mean Linux