每次我编译和运行c文件时,我都必须输入:
gcc filename.c
a.out
我不想分两行进行操作,如何在Linux终端上一行内编译和运行?
您可以使用以下命令将编译和运行合并为一行:gcc filename.c && ./a.out尝试
gcc filename.c && a.out
仅当第一个命令成功时,才会运行第二个命令。请参见https://askubuntu.com/questions/334994/which-one-is-better-using-or-to-execute-multiple-commands-in-one-line
在C语言中,快速而肮脏的解决方案是一个非常糟糕的想法:
gcc myfile.c && ./a.out
如果编译失败,这将不会运行可执行文件,但当编译成功时,即使发出警告,代码也将自动运行;在C语言中,应该始终在运行代码之前至少检查警告。大多数情况下,您应该永远不要运行带有警告的代码。通常,运行具有警告的代码意味着代码存在一些未定义的行为;您不应该盲目地运行这样的代码。当然,在像上面的代码中最低限度使用警告时,可能没有太多的警告,此时应该有一些警告。在绝对最低限度的情况下,应该使用:
gcc myfile.c -Wall -Wextra -Werror && ./a.out
使用-Wall -Wextra
将为许多带来未定义行为的愚蠢错误发出警告,而-Werror
会阻止编译带有警告的代码自动运行。
为了解决这个问题并减少输入量,我过去常常使用这个保存为crepl
的bash脚本:
#!/bin/bash
gcc -std=c99 -Wall -Wextra -Wpedantic -Werror $1 -o tempout &&\
./tempout && rm tempout
当我想快速测试保存在myfile.c
中的一些源代码时,我可以在命令行输入:
crepl myfile.c
如果编译失败,代码将无法运行,如果编译时出现警告,也将无法运行,这要归功于-Werror
。如果编译成功,程序将运行,并在运行后删除临时可执行文件。
自从撰写本答案以来,我已将解决方案演变为稍微花哨的bash脚本,它接受可选的编译器参数、链接库等。
#!/usr/bin/env bash
# crun
#
# A script to invoke gcc, build the executable, execute the binary,
# and cleanup after. The script will exit without running the executable
# if there are any compiler errors or warnings.
#
# This script uses -std=c18, but it could probably be modified so that
# the version is taken from a command-line parameter, defaulting to c18.
#
# Any commands following the crun invocation are appended to CMD.
CMD="gcc -std=c18 -Wall -Wextra -Wpedantic -Werror"
TEMPFILE="tempfile$$"
for ARG in "$@"
do
CMD+=" $ARG"
done
CMD+=" -o ${TEMPFILE} && ./${TEMPFILE} && rm ${TEMPFILE}"
eval $CMD
crun myfile.c -lm
这个技巧可以起到作用,如果有任何错误或警告(它们被调整到合理的级别),则会失败,并在完成后进行清理。
;
来分隔命令,例如:gcc filename.c; ./a.out
然而,如果编译成功后你可能只想运行a.out。为此,你可以使用&&
:
gcc filename.c && ./a.out
解释:
A ; B - 先运行A,然后再运行B,无论A是否成功
A && B - 只有当A成功时才运行B
A || B - 只有当A失败时才运行B
您想知道如何编译和运行程序。 我将告诉您如何编写、编译和运行。
cat << EOF > temp.c && gcc temp.c ; ./a.out ; rm temp.c a.out
#include <stdio.h>
int main(){ printf("%s\n", "Hello World!"); return 0; }
EOF
#!/bin/sh
# GCC in the streams
temp="temp.c"
sgcc() {
(
rm "$temp" # just to be sure
# append every line from shell to the temp file
while read -r l; do printf "%s\n" "$l" >>"$temp"; done
cat "$temp"
gcc "$temp"
exitcode=$?
./a.out
rm "$temp" a.out
exit $exitcode
)
}
您可以像下面这样调用:
sgcc << EOF
#include <stdio.h>
int main(){ printf("%s\n", "Hello World!"); return 0; }
EOF
#include <stdio.h>
int main() {
char a[100];
int a1,b1,sum=0;
fscanf(stdin,"%d %d", &a1,&b1,a);
sum = a1+b1;
fprintf(stdout,"%d\n", sum,a);
return 0;
}
.
在你的PATH
中。这非常可怕。 - Kerrek SB