Linux CC腳本怎樣編寫

小樊
81
2024-10-08 12:15:59

在 Linux 系統(tǒng)中,CC 腳本通常用于編譯 C 或 C++ 代碼。以下是一個(gè)簡(jiǎn)單的 CC 腳本示例,用于編譯名為 hello.c 的 C 語(yǔ)言源文件:

#!/bin/sh

# 檢查參數(shù)數(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

要使用此腳本,請(qǐng)按照以下步驟操作:

  1. 將上述代碼保存為一個(gè)名為 compile_cc.sh 的文件。
  2. 通過運(yùn)行 chmod +x compile_cc.sh 命令使腳本可執(zhí)行。
  3. 使用 ./compile_cc.sh hello.c 命令編譯名為 hello.c 的源文件。

這個(gè)簡(jiǎn)單的腳本接受一個(gè)參數(shù)(源文件名),檢查參數(shù)數(shù)量,確保文件存在,然后使用 gcc 編譯器編譯源文件。如果編譯成功,它將輸出編譯后的可執(zhí)行文件名。

0