cmakeout-of-source

How to tell cmake to generate different default targets for out-of-source-builds?


How can I write a CMakeLists.txt file that accepts different out-of-source builds? I'm not talking about Debug and Release, but more about something like one build for remote testing one for local testing, etc.

For example: If I go into the build_local build directory and run make I want to have the sources compiled for local configration. If I run make in the build_production build directory I want to compile the sources using a different configuration. I understand that out of source builds are what I need. I just don't quite understand how to:

  1. tell cmake what kind of configuration to generate (e.g., cd build_local; cmake -D local?)
  2. how to write a CMakeLists.txt file in a way that it generates different default target (i.e. make all or make) depending on the configuration

Has someone an example or a link to appropriate documentation?

Thanks!


Solution

  • Using if command you can fill default target(and others) with different meanings, dependent of configuration.

    CMakeLists.txt:

    ...
    option(LOCAL "Build local-testing project" OFF)
    if(LOCAL)
        add_executable(program_local local.c)
    else()
        add_executable(program_remote remote.c)
    endif()
    

    local build:

    cd build_local
    cmake -DLOCAL=ON ..
    make
    ...
    

    remote build:

    cd build_remote
    cmake ..
    make
    

    In if branches you can use even different add_subdirectory() commands, so your configured project may completely differ for different configurations.