Using C++ on Linux in VS Code
2021-03-14 처음 작성
컴파일러(g++)를 설치하고 예제프로그램을 동작시켜보죠.
디버그(GDB)도 해 볼 겁니다.
code.visualstudio.com/docs/cpp/config-linux
Get Started with C++ on Linux in Visual Studio Code
Configure the C++ extension in Visual Studio Code to target g++ and GDB on Linux
code.visualstudio.com
참고용 링크입니다.
기본 환경
VSCode를 설치합니다.
Extention for VS Codee
C/C++ extension을 설치합니다.
컴파일러 설치 확인
이미 설치되어 있습니다.
이미 설치되어 있다면 다음 명령어로 확인할 수 있습니다.
gcc -v
제 것은 8.3.0입니다.
디버거(GDB)를 설치합니다.
sudo apt-get update
sudo apt-get install build-essential gdb
예제 파일 생성
mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .
폴더를 생성하고 VS Code를 실행합니다.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}
helloworld.cpp 예제 파일입니다.
추가 생성하게 될 파일들
tasks.json : compiler build settings
launch.json : debugger settings
c_cpp_properties.json : compiler path and Intellisense settings
VSCode에서 새 파일을 생성하여 helloworld.cpp파일로 저장합니다.
빌드
Terminal > Configure Default Build Task.
C/C++ : g++ build activ file. 선택하여
tasks.json파일을 생성합니다.
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++ build active file",
"command": "/usr/bin/g++",
"args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
tasks.json 내용입니다.
Ctrl + Shift + B로 build 합니다.
helloworld 실행파일이 생성됩니다.
실행
./helloworld
디버그
launch.json파일을 만들고
F5로 디버그 할 수 있어요.
우선 Run > Add Configuration.. 을 선택한 후
dropdown 메뉴에서 g++ build and debug active file을 선택합니다.
{
// 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": "g++ - 활성 파일 빌드 및 디버그",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "gdb에 자동 서식 지정 사용",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++ 활성 파일 빌드 ver(1)",
"miDebuggerPath": "/bin/gdb"
}
]
}
launch.json파일이 만들어진다.
"stopAtEntry": false, 를 true로 바꾸면 디버그를 시작하자마자 첫 줄에 정지되어 있어요.
F5 : Continue
F10 : step over
F11 : step into
등과 변수들을 보면서 디버깅 가능합니다.