c++ - 在 Emacs 中保存-编译-执行 C++ 程序的单一快捷方式?

标签 c++ windows emacs g++ user-input

我一直在试图找到一种方法来有效地保存程序,编译它,然后在 emacs 中运行它。我只取得了部分成功。

我使用 smart-compile.el 来简化工作 ( http://emacswiki.org/emacs/smart-compile.el )。 我已经编辑了下面的 C++ 相关部分,以便当我键入 M-x smart-compile RET 后跟 RET 时,程序就会编译并运行。

(defcustom smart-compile-alist '(
  ;; g++-3 is used instead of g++ as the latter does not
  ;; work in Windows. Also '&& %n' is added to run the
  ;; compiled object if the compilation is successful
  ("\\.[Cc]+[Pp]*\\'" . "g++-3 -O2 -Wall -pedantic -Werror 
  -Wreturn-type %f -lm -o %n && %n")
  ..

举个例子,对于一个程序sqrt.cpp,smart-compile自动生成如下编译命令:

g++-3 -O2 -Wall -pedantic -Werror -Wreturn-type sqrt.cpp -lm -o sqrt && sqrt

只要我的 .cpp 没有任何 cin 语句,此操作就有效。对于带有 cin 语句的代码,控制台窗口显示用户应该输入数据的点。但我无法输入任何内容,编译状态一直停留在运行状态。

为了使用户输入的代码正常工作,我必须删除 && FILENAME 部分,然后在 emacs 的 eshell 中手动运行 ./FILENAME .

我在 Windows 中运行 emacs 24.3。我安装了 Cygwin,并将其 bin 添加到 Windows 环境变量 Path(这就是 g++-3 编译工作的原因)。

如果有人能指导我如何使用单个命令在 emacs 中保存、编译和运行用户输入所需的 .cpp 程序,我将不胜感激。或者至少我需要如何修改上面的 g++-3 命令才能使编译+运行适用于用户输入程序。

谢谢!

最佳答案

Emacs 是可编程的,因此如果某件事需要两个步骤,您可以编写一个命令来组合它们。简单的代码如下所示:

(defun save-compile-execute ()
  (interactive)
  (smart-compile 1)                          ; step 1: compile
  (let ((exe (smart-compile-string "%n")))   ; step 2: run in *eshell*
    (with-current-buffer "*eshell*"
      (goto-char (point-max))
      (insert exe)
      (eshell-send-input))
    (switch-to-buffer-other-window "*eshell*")))

上面的代码很简单,但是有一个缺陷:它没有等待编译完成。由于 smart-compile 不支持同步编译标志,因此必须通过临时 Hook compilation-finish-functions 来实现,这使得代码更加复杂:

(require 'cl)  ; for lexical-let

(defun do-execute (exe)
  (with-current-buffer "*eshell*"
    (goto-char (point-max))
    (insert exe)
    (eshell-send-input))
  (switch-to-buffer-other-window "*eshell*"))

(defun save-compile-execute ()
  (interactive)
  (lexical-let ((exe (smart-compile-string "./%n"))
                finish-callback)
    ;; when compilation is done, execute the program
    ;; and remove the callback from
    ;; compilation-finish-functions
    (setq finish-callback
          (lambda (buf msg)
            (do-execute exe)
            (setq compilation-finish-functions
                  (delq finish-callback compilation-finish-functions))))
    (push finish-callback compilation-finish-functions))
  (smart-compile 1))

该命令可以使用 M-x save-compile-execute RET 或将其绑定(bind)到一个键来运行。

关于c++ - 在 Emacs 中保存-编译-执行 C++ 程序的单一快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15723871/

相关文章:

windows - 在 Windows 上安装 PostgreSQL

emacs - Emacs 中 § 符号的键绑定(bind)

emacs - 如何在组织模式HTML导出中禁用自动标题包含?

file-io - Emacs - 当文件被外部修改时通知

c++ - 如何从字符串 vector 中选择第n个位置?

python - 导入 python 包时找不到 Armadillo 库(OS X,Python 2.7)

c++ - 简单的C++模板定义问题

windows - 将外部非版本化资源链接到 SVN 存储库

windows - 监视 COM 对象

c++ - 在实例之间传递另一个类