温馨提示×

centos怎样写c++脚本

小樊
43
2026-10-03 01:41:18
栏目: 编程语言

在 CentOS 上写并运行 C++ 程序(不是严格意义上的“脚本”,但可以被当作脚本来用),一般步骤如下:


一、确认环境

1. 查看是否安装 g++

g++ --version

如果没有安装:

sudo yum install gcc-c++

二、写一个最简单的 C++ 程序

示例:hello.cpp

#include <iostream>

int main() {
    std::cout << "Hello CentOS" << std::endl;
    return 0;
}

三、编译并运行

编译

g++ hello.cpp -o hello

运行

./hello

输出:

Hello CentOS

四、像“脚本”一样使用(可选)

方法 1:加 shebang(不常见,但可行)

#!/usr/bin/g++ -o /tmp/cpp_tmp && /tmp/cpp_tmp
#include <iostream>
int main(){ std::cout << "hi" << std::endl; }

然后:

chmod +x hello.cpp
./hello.cpp

⚠️ 不推荐,编译慢,只是玩具用法。


方法 2:写 shell 包装(推荐)

#!/bin/bash
g++ -std=c++11 test.cpp -o /tmp/test && /tmp/test

五、常用编译参数

g++ -std=c++11 test.cpp -O2 -Wall -o test
  • -std=c++11/14/17
  • -O2 优化
  • -Wall 显示警告

六、写多个文件

g++ main.cpp func.cpp -o app

七、若你想“真脚本语言”

如果你其实想要 像 Python 一样直接运行的脚本,可以考虑:

  • Python
  • C++ + cling
  • C++ + cpp.sh

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

  • 你是 写小工具 / 服务器程序 / 算法题?
  • 用的是 CentOS 7 还是 8 / Stream?

我可以给你更合适的写法。

0 踩