Skip to content

Instantly share code, notes, and snippets.

@Quintus
Created November 29, 2015 11:48
Show Gist options
  • Save Quintus/9c04165215c08b33b048 to your computer and use it in GitHub Desktop.
Save Quintus/9c04165215c08b33b048 to your computer and use it in GitHub Desktop.
Finding the CMake build/ directory in Emacs Lisp (elisp) for compilation
; Add this function to your .emacs file and add it to the c-mode-common hook:
; (add-hook 'c-mode-common-hook 'find-cmake-builddir)
; Afterwards the `compile-command' variable will automatically contain a command for
; building your entire CMake project by just doing `M-x compile' whenever you
; open a C/C++ file inside a CMake-managed project. Sole requirement:
; You first have to manually create a directory "build/" next to your
; CMakeLists.txt file and run CMake with the appropriate options yourself.
(defun find-cmake-builddir ()
"Finds the build directory of a CMake project"
(let ((cmakefile nil) (dirname default-directory))
; Step 1: Find the CMakeFile in the parent directories
; Abort if found or if root dir is reached.
(while (and (not (string= dirname "/")) (not cmakefile))
(setq cmakefile (concat (file-name-as-directory dirname) "CMakeLists.txt"))
(if (not (file-exists-p cmakefile))
(progn
(setq cmakefile nil)
(setq dirname (expand-file-name (concat (file-name-as-directory dirname) ".."))))))
; Step 2: Check if the build directory is there, and if so,
; whether there's a Makefile in it (i.e. cmake has been run)
(if cmakefile
(let ((builddir (concat (file-name-directory cmakefile) "build")))
(if (file-exists-p builddir)
(let ((makefile (concat (file-name-as-directory builddir) "Makefile")))
(if (file-exists-p makefile)
(set (make-local-variable 'compile-command) (concat "make -C " (shell-quote-argument builddir))))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment