如何在 linux 终端中同时为 C++ 代码编译和 运行?

How to compile and run both at the same time for a c++ code in linux terminal?

我正在使用 Ubuntu(最新)。如果我的主目录中有一个 test.cpp 文件,我会在终端中编写两个命令来编译和 运行 这个文件。

prateek332@pp-pc:~$ g++ test.cpp 
prateek332@pp-pc:~$ ./a.out

有没有办法同时写这两个命令(或者更好的方法)。我使用了流水线,但它不起作用。

prateek332@pp-pc:~$ g++ test.cpp | ./a.out

这行不通。它不会编译为 test.cpp 文件中的新更改,而只是 运行 文件中的旧代码。

g++ test.cpp && ./a.out 首先编译,然后,如果成功,运行 代码。

您可以创建一个 shell 函数,因为这是您经常做的事情。

~/.bashrc 中(或者你的 shell 配置类似于 ~/.zshrc)

function cpp() { g++  && ./a.out; }

现在您只需输入

cpp test.cpp

您可以随意命名该函数。新开一个shellwindow加载函数(或者运行source ~/.bashrc)。