在 Linux 下用 C++ 写“脚本”,一般有两种常见理解,我分别说明,并给出可直接用的示例。
虽然 C++ 不是脚本语言,但你可以通过 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
✅ 优点:像脚本
❌ 缺点:每次都重新编译,慢
clang + tcc / cling(真正脚本化)sudo apt install cling
#include <iostream>
std::cout << "Hello\n";
运行:
cling script.cpp
✅ 真正“C++ 脚本”
❌ 生态不如 Python
如果你是 写 Linux 工具 / 自动化脚本,通常是:
#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);
}
| 场景 | 建议 |
|---|---|
| 简单自动化 | Bash |
| 复杂逻辑 | C++ |
| 高性能 | C++ |
| 快速开发 | Python |
| 系统底层 | C++ |
std::filesystem(C++17)std::process(C++23 / 第三方)Linux 下 C++ 不是“脚本语言”,但你可以:
- 用 shebang 模拟脚本
- 用 cling 当解释器
- 用 C++ 写系统工具替代 shell
如果你愿意,可以告诉我:
我可以直接给你一套模板。