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

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

本文关键字:编译 运行 c++ 代码 linux 终端      更新时间:2023-10-16

我使用的是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++ $1 && ./a.out; }

现在您只需键入

cpp test.cpp

您可以随意命名函数。打开一个新的shell窗口以加载函数(或运行source ~/.bashrc(。