前言
我初次使用visual studio code 编译c++,本文是我的一些不算成熟的经验,仅供参考。
文中先是我遇到的一些报错与解决方法,然后是tasks.json,c_cpp_properties.json,launch.json基本配置文件的配置。
因为cscode只是轻量级的代码编辑器,需要安装c++相关的插件和编译器,我使用的是的c++编译器是mingw64,安装编译器的教程可以在网上搜到。
一、初次使用vscode 遇到的报错
C:\Program Files\vscode\vsspace\demo1\arraydemo\myarray.cpp:44:28: error: 'endl' was not declared in this scope
cout<<"xigoufunction"<<endl;
^~~~
C:\Program Files\vscode\vsspace\demo1\arraydemo\myarray.cpp:44:28: note: 'std::endl' is defined in header '<ostream>'; did you forget to '#include <ostream>'?
//提示需要引入#include<ostream>,将该头文件引入就好
类似这个error: 'endl' was not declared in this scope,除了要引进相关头文件之外还需要在添加 using namespace std;
二、引用自己定义的.h头文件
1.引用当前项目文件夹定义很多头文件
引用当前工作空间的头文件,需要配置c_cpp_properties.json文件,配置如下:
{
"configurations": [
{
"name": "Win32",
"includePath": [//项目引入头文件的路径
"${workspaceFolder}/**" ,//这一句就是引用当前项目文件空间所有的头文件,包括多层文件夹中的头文件
"D:\\Program Files\\mingw64\\bin\\demo\\**"//引入自定义路径头文件
],
// "forcedInclude": ["${workspaceFolder}\\arraydemo\\*"],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "gcc-x64",
"compilerPath": "D:\\Program Files\\mingw64\\bin\\g++.exe"
}
],
"version": 4
}
其中"${workspaceFolder}/**" 意思是引入当前工作目录的所有头文件,包括当前目录文件内的头文件。如果你需要引用别的路径的头文件,那需要自己手动添加路径到 includePath的字典中
2.多个文件进行编译
当一个项目有多个cpp文件需要编译的时候,需要在task.json文件中手动添加编译的文件,是否有自动添加的配置选项暂时没有了解到过。
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++.exe build active file",
"command": "D:\\Program Files\\mingw64\\bin\\g++.exe",
"args": [
"-g",
"${file}",//表示编译当前打开的文件
"${workspaceFolder}\\arraydemo\\myarray.cpp",//添加需要一起编译的cpp文件
"-I",
"--std=c++17",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "D:\\Program Files\\mingw64\\bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
主要是在args字典中添加cpp文件,"${file}"表示编译当前打开的文件。
3.lauch.json文件配置
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"preLaunchTask": "g++.exe build active file",
"type": "cppdbg",//只能为cppdbg
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",//调试程序的路径名称
"args": [],//调试传递参数
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "D:\\Program Files\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
luanch.json的配置文件我暂时没有遇到需要配置的地方,这是我网上找的配置。
总结
本文就vscode编译多个文件,引用自定义头文件相关配置做了一些分析,仅供初学者参考。