---
title: "改造Emacs compile命令"
author: "ppgunjack"
date: "2011-10-12T15:30:38Z"
tags: []
categories: ["非技术"]
slug: "emacs-compile"
draft: false
lastmod: "2011-10-12T15:30:38Z"
id: 1190774
url: "https://ppgunjack.iteye.com/blog/1190774"
---

修改的compile命令，为emacs实现快捷键绑定的编译功能：

F9编译，没有存的文件会提示存盘

C-F9是无提示的直接存盘+编译。

 

编译是编译的当前buffer文件，即在任何buffer窗口中按下'F9'或者'C-F9'，都会直接编译该buffer对应的代码文件。

默认参数是使用g++ -g并加入了一些常用的库文件和头文件，路径做成list列表可能会更方便，这个以后闲了再改造。

 

特性：

1.编译当前buffer，生成的执行文件名是默认以当前buffer为名生成+".exe"后缀，在编译完之后会被立刻调用，如果你是linux下用记得在compile-command里面改改后缀以及注意在执行文件前加'./'。

2.缩小的compile窗口（只占emacs窗体1/4），避免其和代码窗口平分屏幕，尤其是代码窗口和compile窗口是上下分布的情况，这点更为重要。

3.编译和执行过程中焦点会始终保持在所编译的代码buffer的窗口，不会切到compile窗口或者其他窗口。

 

好处：

特别适合编译那些小demo，算法演示一类的代码，避开维护笨重的make

 

下面是code（需要把这些code加入到文件\_emacs或者.emacs）：

 

;;下面代码保证emacs在新打开compile窗口的时候只会水平分割窗口

(setq split-height-threshold 0)

(setq split-width-threshold nil)

 

 

;;编译

;; F9 调用 compile 并设置编译命令

;; C-F9 则保存所有文件并编译(无提示)

(defun defineCompileCmd()

  (interactive)

  (setq boost\_path 

"E:/workspace/C++/lib/boost/boost1.46")

  (setq ace\_src\_path 

"E:/workspace/C++/lib/ace/ace6.0.4/ACE\_wrappers")

  (setq ace\_include\_path 

"E:/workspace/C++/lib/ace/ace6.0.4/ace/include")

  (setq ace\_mingw\_lib\_d 

"E:/workspace/C++/lib/ace/ace6.0.4/ace/lib\_gcc/lib\_d")

  (setq ace\_mingw\_lib 

"E:/workspace/C++/lib/ace/ace6.0.4/ace/lib\_gcc/lib")

  (setq compile\_file\_name (substring (buffer-name (current-buffer)) 0 (string-match "\[.]"  (buffer-name (current-buffer)))))

  (setq compile\_file\_name (concat compile\_file\_name ".exe"))

  (setq compile-command 

(concat  "g++ -g -I"

boost\_path

" -I"

ace\_src\_path

" -I"

ace\_include\_path

" -L"

ace\_mingw\_lib

" -lACE " 

(buffer-name (current-buffer))

" -o "

compile\_file\_name

" && "

compile\_file\_name

))

  )

 

(defun shrink-compile-window()

  "shrink compile window, avoid compile window occupy 1/2 hight of whole window"

  (interactive)

  ;;(select-window (get-buffer-window "\*compilation\*"))

  (setq compiled\_buffer\_name (buffer-name (current-buffer)))

  (switch-to-buffer-other-window "\*compilation\*")

  (if (&lt; (/ (frame-height) 3) (window-height))

      (shrink-window (/ (window-height) 2)))

  (switch-to-buffer-other-window compiled\_buffer\_name)

  )

 

;;C-F9保存当前所有未保存的buffer并编译当前buffer

(global-set-key \[C-f9] '(lambda()

 "Save buffers and start compile"

 (interactive)

 (save-some-buffers t)

 (defineCompileCmd)

 (compile compile-command)

 (shrink-compile-window)

 )

) 

;;F9调用compile编译当前buffer

(global-set-key \[f9] '(lambda ()

(interactive)

(defineCompileCmd)

(compile compile-command)

(shrink-compile-window)

)

)

 

 

在emacs的代码窗口，按下F9或者C-F9，编译并运行文件，效果如下：

![](http://dl.iteye.com/upload/attachment/568859/28861cbf-45c8-3b92-b510-baca8da691f6.png)