Tinkering with VS Code, MacOS and C++

Build, run and debug C++ code using VS Code for Mac

After a long time, I got the time to tinker with something fun and learn from it, thanks to the week-long break from work. The task at hand is to set up Visual Studio for Mac to compile/run/debug C++ programs. Why, you may wonder - for the past few months, I have been craving to learn something different and I was hooked when I saw the book Data Structures and Algorithms in C++ by Adam Drozdek. I decided to read this book and learn from it.

My goal is to configure Visual Studio for Mac for C++. The first step is to install the C/C++ extension for VSCode, which was pretty straight-forward as described in VS Code instructions. Note that this extension does not include the compiler and debugger, so we need to install them on our own and configure the extension to use them. Good news is that Clang is already available on my machine as part of the Xcode toolchain.

Configuring VS Code to use Clang is described well in this official documentation, almost - except one thing. The article explains how to write a simple C++ program ,compile and run it from within VS Code using the tasks.json config file. It goes on to explain the next step of debugging the code, which opened up one of the rabbit holes for me because of a subtle nuance in the description. Basically, VS Code defines the debug configuration in the file launch.json which includes a setting named preLaunchTask whose value should match the name of the task in the file tasks.json. This specific detail was not called out in the steps, and there was a mismatch in these files auto-generated by the config.

So whenever I try to debug the code (using F5), the compiler threw the error saying that C++ 11 extensions cannot be used, even though I had configured my tasks.json to use the C++ 17 compiler. After some digging around, I found the correlation between the two files, modified it and viola, everything started working. It was satisfying to see that I can run, debug, put breakpoints, step through/over C++ code, all within Visual Studio Code.

I spent the next couple of hours writing the notes and trying out the exercises in the first chapter of the book. I am writing all the code and Obsidian notes in my github repo Book Learnings. Looking forward to learning a ton and enjoying the happy place this week!

comments powered by Disqus