1、C++代码的基础结构
#include <iostream> /*C++ 标准库的头文件
using namespace std; /*让编译器去std命名空间找(cout=std::cout)
int main()
{
cout << "Hello world!" << endl;
return 0; /*返回值语句,正常运行的中断
}
总结
1.程序编译前,先执行预处理部分
2.main函数为称之为主函数,程序执行的入口
3.main函数内部为功能代码,每一行需要;结尾
4.cout<<“内容”<< endl;可以将内容输出
5.return0;为返回值语句固定写法
2、安装编译器
1、可以执行C++代码编译工作的编译器有很多,我们选择下载mingw
2、安装后再选中mingw32-base和mingw32-gcc-g++进行安装
3、将安装后的bin目录添加到环境变量(win键搜索高级系统设置)
3、(可选)配置VScode环境
在项目文件夹新建.vscode文件夹
创建3个文件
1、c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": ["${workspaceFolder}/**"],
"defines": ["_DEBUG", "UNICODE", "_UNICODE"],
"windowsSdkVersion": "10.0.17763.0",
"compilerPath": "D:\\dev\\sdk\\mingw\\bin\\g++.exe", /*修改成自己bin目录下的g++.exe,这里的路径和电脑里复制的文件目录有一点不一样,这里是两个反斜杠\\*/
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "${default}"
}
],
"version": 4
}
2、launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "g++.exe build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "D:\dev\sdk\mingw\bin\gdb.exe", /修改成自己bin目录下的gdb.exe,这里的路径和电脑里复制的文件目录有一点不一样,这里是两个反斜杠\/
"setupCommands": [
{
"description": "为 gdb 启用整齐打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "task g++"
}
]
}
3、tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "task g++",
"command": "D:\dev\sdk\mingw\bin\g++.exe", /修改成自己bin目录下的g++.exe,这里的路径和电脑里复制的文件目录有一点不一样,这里是两个反斜杠\/
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\${fileBasenameNoExtension}.exe",
"-I",
"D:\dev\code\cpp\itheima_cpp", /修改成自己放c/c++项目的文件夹,这里的路径和电脑里复制的文件目录有一点不一样,这里是两个反斜杠\/
"-std=c++17"
],
"options": {
"cwd": "D:\dev\sdk\mingw\bin" /修改成自己bin目录,这里的路径和电脑里复制的文件目录有一点不一样,这里是两个反斜杠\/
},
"problemMatcher":[
"$gcc"
],
"group": "build",
}
]
}
配置完成后按F5即可运行程序
代码在return前需加入system(“pause”);来防止窗口立刻关掉