1

My project directory contains a CMakeLists.txt file and src and include directories at its root. src also contains its own CMakeLists.txt, which is linked by the one at the root. Is there a way I can specify to CMake to set a default global build directory so that the syntax in src/CMakeLists.txt is close to the following?

include_directories(include)
add_executable(first main.cpp foo.cpp)
add_executable(second bar.cpp)

I would like this directory tree to be built:

CMakeLists.txt

src/
    CMakeLists.txt
    main.cpp
    foo.cpp
    bar.cpp

include/
    ...

bin/ (or build/)
    first
    second
Vortico
  • 2,610
  • 2
  • 32
  • 49

1 Answers1

7

You could set CMAKE_RUNTIME_OUTPUT_DIRECTORY:

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)

However, this won't create subdirectories inside bin/ for each different target.

If you want that, you could create a helper function to wrap add_subdirectories:

function(my_add_executable TargetName)
  set(Files ${ARGV})
  list(REMOVE_AT Files 0)
  add_executable(${TargetName} ${Files})
  set_target_properties(${TargetName} PROPERTIES
                            RUNTIME_OUTPUT_DIRECTORY
                                "${CMAKE_SOURCE_DIR}/bin/${TargetName}")
endfunction()

then simply change your calls to:

my_add_executable(first main.cpp foo.cpp)
my_add_executable(second bar.cpp)


For further details, run

cmake --help-variable "CMAKE_RUNTIME_OUTPUT_DIRECTORY"
cmake --help-property "RUNTIME_OUTPUT_DIRECTORY"
cmake --help-property "RUNTIME_OUTPUT_DIRECTORY_<CONFIG>"
Fraser
  • 74,704
  • 20
  • 238
  • 215
  • 1
    This works perfectly for me. Although I don't have a use for it yet, the directory-per-executable method is a great idea as my codebase grows and the binaries become more disorganized in a single folder. Also, I wasn't aware a reference feature was available from the `cmake` program itself. (I remember replying earlier today, but I don't see the message, so apologies if this is a double post.) – Vortico Jun 15 '12 at 01:08