温馨提示×

怎样用linux c++写脚本

小樊
44
2026-10-22 16:01:46
栏目: 编程语言

在 Linux 下用 C++ 写“脚本”,一般有两种常见理解,我分别说明,并给出可直接用的示例。


一、把 C++ 当“脚本”用(推荐方式)

虽然 C++ 不是脚本语言,但你可以通过 shebang + 编译缓存 的方式,让它用起来像脚本。

方式 1:直接用 g++ + shebang(最简单)

示例:hello.cpp

#!/usr/bin/env g++ -std=c++17 -o /tmp/hello$$ -x c++ -- && /tmp/hello$$

#include <iostream>

int main() {
    std::cout << "Hello from C++ script!\n";
    return 0;
}

使用

chmod +x hello.cpp
./hello.cpp

✅ 优点:像脚本
❌ 缺点:每次都重新编译,慢


方式 2:用 clang + tcc / cling(真正脚本化)

使用 Cling(C++ 解释器,最接近脚本)

sudo apt install cling
#include <iostream>
std::cout << "Hello\n";

运行:

cling script.cpp

✅ 真正“C++ 脚本”
❌ 生态不如 Python


二、用 C++ 写 Linux 系统脚本(系统编程)

如果你是 写 Linux 工具 / 自动化脚本,通常是:

  • 文件操作
  • 执行 shell 命令
  • 进程管理
  • 定时任务

示例:C++ 执行 shell 命令

#include <cstdlib>

int main() {
    system("ls -l > output.txt");
}

或更安全:

#include <array>
#include <iostream>
#include <cstdio>

int main() {
    std::array<char, 128> buffer;
    FILE* pipe = popen("ls -l", "r");
    while (fgets(buffer.data(), buffer.size(), pipe)) {
        std::cout << buffer.data();
    }
    pclose(pipe);
}

三、C++ 替代 shell 脚本的常见场景

场景 建议
简单自动化 Bash
复杂逻辑 C++
高性能 C++
快速开发 Python
系统底层 C++

四、推荐实践(像写脚本一样写 C++)

  1. 用 std::filesystem(C++17)
  2. 用 std::process(C++23 / 第三方)
  3. 写成小工具 + Bash 调用

五、总结一句话

Linux 下 C++ 不是“脚本语言”,但你可以:

  • 用 shebang 模拟脚本
  • 用 cling 当解释器
  • 用 C++ 写系统工具替代 shell

如果你愿意,可以告诉我:

  • 你是想 自动化任务
  • 还是 写系统工具
  • 还是 替代 Bash/Python

我可以直接给你一套模板。

0 踩