介绍与编译运行

翻译整理自 cppreference - C++ 历史 与 Microsoft C++。

1. C++ 简史

  • 1979 Bjarne Stroustrup 在贝尔实验室设计 “C with Classes”
  • 1985 Cfront 1.0,C++ 正式商用
  • 1998 ISO C++98 标准
  • 2003 C++03 修复缺陷
  • 2011 C++11 大跃进:auto、lambda、移动语义、智能指针、并发
  • 2014 C++14:泛型 lambda、二进制字面量
  • 2017 C++17:filesystem、optional、variant、structured bindings
  • 2020 C++20:concept、ranges、modules、coroutines
  • 2024 C++23:std::expected、std::print、更完整的协程

2. 安装编译器

Windows

  • Visual Studio 2022:内置 MSVC
  • MinGW-w64:GCC for Windows
  • LLVM Clang

macOS

xcode-select --install      # 自带 clang
brew install llvm           # 新版 clang

Linux

sudo apt install g++ clang
g++ --version

3. Hello World

hello.cpp:

#include <iostream>

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

编译与运行:

g++ -std=c++17 hello.cpp -o hello
./hello

4. 编译参数

参数 含义
-std=c++20 指定标准
-O2 / -O3 优化级别
-g 调试信息
-Wall -Wextra -Wpedantic 警告
-I<path> 头文件搜索
-L<path> -l<lib> 库搜索与链接
-pthread 链接 pthread
-fsanitize=address ASan 内存检测

推荐:

g++ -std=c++20 -Wall -Wextra -Wpedantic -O2 -g hello.cpp -o hello

5. 程序结构

#include <iostream>       // 预处理指令
#include <vector>          // 标准库容器
#include "mylib.h"         // 用户头文件

namespace mylib {          // 命名空间
    int add(int a, int b); // 函数声明
}

int main() {
    return 0;
}

6. C 与 C++ 的关键区别

特性 C C++
注释 仅 /* */(C99+ 才有 //) // 与 /* */
函数声明 可省略原型 必须声明
默认返回 int int(仍需写)
内存分配 malloc/free new/delete 与 RAII
字符串 char* + <string.h> std::string
IO printf/scanf std::cout/cin
模板 无 template<typename T>
异常 无 try/catch/throw
命名空间 无 namespace
引用 无 int& r = x;

小结

到此已经能编写、编译、运行 C++ 程序。下一章学习基本语法。