温馨提示×

Linux CC脚本怎样编写

小樊
81
2024-10-08 12:15:59
栏目: 智能运维

在 Linux 系统中,CC 脚本通常用于编译 C 或 C++ 代码。以下是一个简单的 CC 脚本示例,用于编译名为 hello.c 的 C 语言源文件:

#!/bin/sh

# 检查参数数量
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <source_file>"
    exit 1
fi

# 获取源文件名
source_file="$1"

# 检查文件是否存在
if [ ! -f "$source_file" ]; then
    echo "Error: File not found - $source_file"
    exit 1
fi

# 编译源文件
gcc -o "$source_file".out "$source_file"

# 检查编译是否成功
if [ $? -eq 0 ]; then
    echo "Compilation successful: $source_file.out"
else
    echo "Error: Compilation failed for - $source_file"
    exit 1
fi

要使用此脚本,请按照以下步骤操作:

  1. 将上述代码保存为一个名为 compile_cc.sh 的文件。
  2. 通过运行 chmod +x compile_cc.sh 命令使脚本可执行。
  3. 使用 ./compile_cc.sh hello.c 命令编译名为 hello.c 的源文件。

这个简单的脚本接受一个参数(源文件名),检查参数数量,确保文件存在,然后使用 gcc 编译器编译源文件。如果编译成功,它将输出编译后的可执行文件名。

0