VS Code로 C++ 디버깅하기
이 글은 Visual Studio Code(VS Code)에서 디버깅 환경을 설정하는 방법을 설명한다. 여기서 설명하는 설정은 macOS용이지만, 컴파일러 값 등 최소한의 변경으로, Windows에서도 쉽게 적용할 수 있다. VS Code는 빌드와 디버그 설정을 위해 tasks.json과 launch.json을 사용한다. 이 파일들을 설정하고 사용하는 방법을 설명한다.
태스크 설정 (tasks.json)
tasks.json 파일은 VS Code의 자동화된 작업들을 정의한다. 아래는 C++ 코드를 빌드하기 위한 예제 설정이다.
// tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build", // The name of the task. It is referenced in launch.json as preLaunchTask.
"type": "shell", // The type of task. "shell" indicates the task runs in the terminal.
"command": "g++", // The command to run. Here, the GNU C++ compiler is used.
"args": [
"-std=c++17", // Specifies the C++17 standard.
"-g", // Generates debugging information.
"${fileDirname}/*.cpp", // Compiles all .cpp files in the current directory.
"-o",
"${workspaceFolder}/build/main" // Specifies the output path and executable name.
],
"group": "build" // Assigns this task to the 'build' group.
}
]
}
설명
"command": "g++": GNU C++ 컴파일러로 소스 파일을 컴파일한다.-std=c++17: C++17 표준을 사용한다.-g: 디버깅 정보를 포함한다."${fileDirname}/*.cpp": 현재 경로의 모든 .cpp 파일을 대상으로 한다.-o "${workspaceFolder}/build/main": 출력 실행 파일 경로를 설정한다."label": "build": 작업의 이름을 설정한다. 이 라벨은 디버깅 전에 빌드 작업을 실행하기 위해 launch.json 파일에서 사용할 수 있다.
디버그 설정 (launch.json)
launch.json 파일은 VS Code의 디버깅 환경을 설정한다.
// launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "debug", // Name of the debugging configuration, shown in VS Code.
"type": "cppdbg", // Specifies the C++ debugger type.
"request": "launch", // Indicates whether to launch a program or attach to a running process.
"program": "${workspaceFolder}/build/main", // Path to the executable to debug.
"args": [], // Arguments to pass to the program when it starts.
"stopAtEntry": false, // Whether to break at the entry point of the program.
"cwd": "${fileDirname}", // Sets the current working directory.
"environment": [], // Defines environment variables for the debugging session.
"externalConsole": false, // Uses the internal VS Code console instead of an external one.
"MIMode": "lldb", // Specifies the debugger backend (LLDB for macOS).
"preLaunchTask": "build" // Runs the "build" task before starting the debugger.
}
]
}
설명
"program": 디버거에서 실행할 빌드된 실행 파일을 지정한다."preLaunchTask": "build": 디버깅 세션을 시작하기 전에 “build” 작업을 실행한다."MIMode": "lldb": macOS의 기본 디버거인 LLDB를 사용한다.
사용 방법
- VS Code에서 디버깅 탭을 연다.
- 드롭다운 메뉴에서 “debug” 설정을 선택한다.
- 초록색 재생 버튼을 클릭하여 디버깅을 시작한다.
- VS Code가 기본 파일이 아니라 위 설정 파일들을 사용하는지 확인한다.
VS Code는 먼저 tasks.json 설정을 이용해 프로젝트를 빌드한다. 빌드가 완료되면 디버거가 실행 파일을 실행한다.