4

Sometimes I forget I'm in the build folder and I run the command in the root directory. Well, maybe some of you have experienced that this creates a mess in the entire file hierarchy, as you have to delete CMakeFiles/ folder, config files, and files related to CPack and CTest. Is there a way I can add something to the Makefile at the root directory that prevents me from running cmake accidentally? I tried to add a target 'cmake' but this didn't work.

aa

UPDATE

I found the same question posted in here. I ended up adopting to put a function in my .bashrc file as suggested in that page:

function cmake() {
  # Don't invoke cmake from the top-of-tree
  if [ -e "CMakeLists.txt" ]
  then
    echo "CMakeLists.txt file present, cowardly refusing to invoke cmake..."
  else
    /usr/bin/cmake $*
  fi
}
Community
  • 1
  • 1
aaragon
  • 2,314
  • 4
  • 26
  • 60

1 Answers1

6

You can check in your CMakeLists.txt if the source and binary directories are the same. Put something like this as the very first thing in your CMakeLists.txt:

if (CMAKE_BINARY_DIR STREQUAL CMAKE_SOURCE_DIR)
    message(FATAL_ERROR "Source and build directories cannot be the same.")
endif()
JesperE
  • 63,317
  • 21
  • 138
  • 197
  • 1
    Great @JesperE, that made it! Almost. The problem now is that this still creates CMakeCache.txt and the CMakeFiles/ directory. – aaragon Jul 02 '14 at 10:43
  • 1
    Yes, this does not seem possible to avoid, unfortunately. I think these files are created even before control is passed to the CMakeLists.txt file. – JesperE Jul 02 '14 at 11:09
  • 1
    BUT You can clean it up in this case :} `file (REMOVE CMakeCache.txt)` , to be precise. – Kamiccolo Jul 02 '14 at 12:59
  • `file (REMOVE CMakeCache.txt)` does not actually work, because it appears to execute before the file is created. Strangely, CMake seems to create the file _after_ FATAL_ERROR. It's odd that CMake would strongly encourage out-of-source builds (for good reason!), and then make it so hard to prevent accidental in-source builds. – CXJ Oct 06 '14 at 04:26