gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:34:11 25 4
gpt4 key购买 nike

我一直在努力找出一种有效地保存程序、编译程序然后在 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 auto生成如下编译命令:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com