emacs C语言编译自动关联当前cpp文件

Vim、Emacs配置和使用
回复
cuiaoxiang
帖子: 62
注册时间: 2010-02-01 19:08

emacs C语言编译自动关联当前cpp文件

#1

帖子 cuiaoxiang » 2010-07-18 9:01

我现在是用 Makefile 的,或者在 M-x compile 以后的minibuffer里修改需要编译的命令
怎么设置使得 emacs 自动关联文件名?

比如在 a.cpp 窗口编译默认的是 g++ a.cpp -g -Wall -o test
b.cpp 就自动变成 g++ b.cpp -g -Wall -o test
God grant me the serenity to accept the things I cannot change
the courage to change the things I can
the wisdom know the difference
头像
hzwjy
帖子: 28
注册时间: 2006-09-26 21:02

Re: emacs C语言编译自动关联当前cpp文件

#2

帖子 hzwjy » 2010-07-18 22:01

代码: 全选

;;================================
;; 快速编译单个文件
;;================================
(provide 'mycompile)

(defvar compile-guess-command-table
  '((c-mode       . "gcc -Wall -g %s -o %s -lm"); Doesn't work for ".h" files.
    (c++-mode     . "g++ -g %s -o %s -lm")	; Doesn't work for ".h" files.
    (fortran-mode . "pgf77 %s -o %s.exe")
    (f90-mode . "pgf90 %s -o %s.exe")
    )
  "*Association list of major modes to compilation command descriptions, used
by the function `compile-guess-command'.  For each major mode, the compilation
command may be described by either:

  + A string, which is used as a format string.  The format string must accept
    two arguments: the simple (non-directory) name of the file to be compiled,
    and the name of the program to be produced.

  + A function.  In this case, the function is called with the two arguments
    described above and must return the compilation command.")

;; This code guesses the right compilation command when Emacs is asked
;; to compile the contents of a buffer.  It bases this guess upon the
;; filename extension of the file in the buffer.

(defun compile-guess-command ()

  (let ((command-for-mode (cdr (assq major-mode
				     compile-guess-command-table))))
    (if (and command-for-mode
	     (stringp buffer-file-name))
	(let* ((file-name (file-name-nondirectory buffer-file-name))
	       (file-name-sans-suffix (if (and (string-match "\\.[^.]*\\'"
							     file-name)
					       (> (match-beginning 0) 0))
					  (substring file-name
						     0 (match-beginning 0))
					nil)))
	  (if file-name-sans-suffix
	      (progn
		(make-local-variable 'compile-command)
		(setq compile-command
		      (if (stringp command-for-mode)
			  ;; Optimize the common case.
			  (format command-for-mode
				  file-name file-name-sans-suffix)
			(funcall command-for-mode
				 file-name file-name-sans-suffix)))
		compile-command)
	    nil))
      nil)))

试试用这个。使用时还是用compile命令。
当然,为了使用你所要求的编译参数,你要修改下compile-guess-command-table的内容。
lct721521
帖子: 15
注册时间: 2010-03-26 8:27

Re: emacs C语言编译自动关联当前cpp文件

#3

帖子 lct721521 » 2010-07-19 19:35

嗯,不错
回复