#8: Introduction to IDEs + Debugging and Profiling
Part 1: IDEs
Context: Using IDEs
Throughout the missing semester sessions we have come across various command line tools such as the shell, editors, version control systems and containers. Knowing these from the command line is invaluable, especially on remote machines without a UI such as connection over SSH.
However, it is often more convenient to use these tools through a graphical interface. This is where IDEs (Integrated Development Environments) come in. IDEs are applications that combine a graphical text editor with interfaces to many of the tools we’ve already covered, such as git, compilers, build toolchains and debuggers which makes our lives as developers so much easier!
NOTE: These notes supplement the talk rather than replace it, as many of the IDEas (peak comedy) covered in this session will be shown via live demos. If you missed the talk, there are plenty of online guides for every VS Code feature (that probably also go much further in depth).
Editors vs. IDEs
Earlier in the course we looked at terminal editors like nano and Emacs (from previous sessions!):
- nano is a pure text editor: open a file, change it, save it. It knows nothing about your project or language.
- Emacs and Vim are extensible editors. With enough configuration and plugins they can do much of what an IDE does.
- An IDE has that integration built in, and understands your project as a whole rather than just the open file.
Features an IDE gives you out of the box, which nano lacks and Emacs/Vim need plugins or configuration for:
- Code completion
- Go to definition / find all references
- Refactoring (e.g. renaming a variable everywhere)
- Errors and warnings shown as you type
- Building, running and graphically debugging code
- A version control UI and an integrated terminal
The trade-off: nano and Emacs/Vim work anywhere over plain SSH and can usually be found to already be installed on alot of distributions (e.g. VI), while IDEs usually need extra setup for remote work and are alot larger in package size!
Much of this “language intelligence” comes from the Language Server Protocol (LSP): a “language server” (e.g. pyright for Python, clangd for C/C++, rust-analyzer for Rust) understands your code, and any editor that speaks LSP can use it, including VS Code, Emacs and Neovim. (Which is why many people can get away (or just prefer) using VIM / Emacs as replacement over standard IDEs)
IDEs in Industry
In most tech jobs you’ll spend much of your day in an IDE. Things you’ll likely come across:
- Ecosystem conventions: IntelliJ IDEA for Java/Kotlin, Visual Studio for .NET and game dev, Xcode for iOS/macOS, Android Studio for Android, and VS Code nearly everywhere else.
- Shared team config: repos may include a
.vscode/folder or equivalent with recommended extensions, debug configurations and settings so everyone’s setup matches and can get to work straight away! - Remote development: editing locally while code runs over SSH, in containers, or in the cloud (e.g. GitHub Codespaces).
- Dev containers enables development entirely within a container. All the advantages of Docker as explained previously!
- AI assistants: tools like GitHub Copilot and Cursor are common, but many companies restrict which ones can be used with their code.
Choice of IDE
What IDE you pick depends on the features you want, the language you use and your budget. Some are free and open source, some freeware, some paid (though JetBrains IDEs are free for us students).
For example, Python comes with IDLE, a barebones IDE that’s fine for beginners but lacks more powerful features. Python developers often move to JetBrains’ PyCharm, or a general-purpose IDE like VS Code.
Common alternative IDEs
- JetBrains’ suite (free + paid options)
- IntelliJ IDEA (Java, Kotlin)
- PyCharm (Python)
- CLion (C, C++)
- Platform-specific
- Android Studio (Android)
- Visual Studio (.NET, C++)
- FOSS options
- Eclipse (Java)
- NetBeans (Java)
- VSCodium (community built binary of VS Code)
- Others
- Cursor (AI-focused fork of VS Code)
Visual Studio Code
We will use VS Code in this session, since it is powerful, versatile and lightweight (and also my personal choice for longer tasks like writing these notes). It supports many languages out of the box and many more through its extensions marketplace. It even comes with “Chat”, an AI agent (opinions on that left as an exercise for the reader…). If you want fully open-source builds without Microsoft’s additions, try VSCodium.
It doesn’t really matter which IDE you use. Everything shown today (explorer, search, git, running code, breakpoints, stepping, inspecting variables etc) exists in practically every modern IDE with different buttons and shortcuts. Some IDEs are just better suited to certain languages (or just personal preference).
Demo - basic overview
- Basic panel layout and opening a folder
- File editing, search (and replace)
- Command Palette and settings
- Word wrap
Useful Windows/Hotkeys
On macOS, use cmd instead of ctrl.
- Explorer (
ctrl+shift+e): the files and directories in your project. - Terminal (
ctrl+`): a built-in terminal with all the tools we’ve looked at before! - Command Palette (
ctrl+shift+p): search for and run almost any command. If you remember one shortcut, make it this one. - Quick Open (
ctrl+p): jump to any file by name. - Search (
ctrl+shift+f): search across all files in the project. - Source Control (
ctrl+shift+g): interface with git. - Run and Debug (
ctrl+shift+d): launch and control the debugger. - Extensions (
ctrl+shift+x): browse and install extensions.
Extensions
Out of the box, VS Code is closer to a smart text editor. Extensions are what turn it into a Python IDE, a C++ IDE, a LaTeX editor, and so on, usually by adding a language server and a debugger.
Finding the extensions you need
- Open a file: VS Code will often recommend the official extension for that file type.
- Search the Marketplace for the language or framework, preferring verified publishers and official extensions.
- Check the docs: the VS Code language guides and most frameworks’ “editor setup” pages list what to install.
- Check the repo: projects often include
.vscode/extensions.json; search@recommendedin the Extensions view to see them.
Useful Extensions
- Python + Pylance + Python Debugger
- C/C++
- rust-analyzer
- Jupyter
- Markdown Preview
- LaTeX Workshop
- Hex Editor
- Docker
- Gradle
- Dev Containers
- Remote - SSH
- GitLens
Security Notice
VS Code’s extensions are powerful but the marketplace is a community marketplace where anyone can upload code, and it doesn’t have to be open source, so you are effectively running others’ code blindly.
Some authors are verified (e.g. Microsoft’s official extensions), and ratings, age and download counts can help, but don’t rely on these alone. Attacks via extensions can and do occur, especially AI-themed ones!
Git Integration
The Source Control view (ctrl+shift+g) is a graphical front end to the same git commands from the version control lecture:
- +/- indicators show added, modified or deleted lines.
- Clicking a changed file opens a side-by-side diff.
+stages a file (git add), and you can stage individual lines from the diff (git add -p).- The message box commits (
git commit -m), and sync pushes/pulls. - The branch name in the status bar switches or creates branches (
git switch). - Merge conflicts get “Accept Current / Incoming / Both” buttons and a merge editor.
The GUI is great for reviewing diffs, but probably best to still know the commands too!
Demo - Running a Python file
- Install the Python extension (this also installs Pylance and the Python Debugger).
- Open a folder and create
average.py. - Check the selected interpreter in the bottom-right of the status bar (or run
Python: Select Interpreter). - Write the code:
def average(numbers):
total = 0
for i in range(1, len(numbers)):
total += numbers[i]
return total / len(numbers)
scores = [72, 85, 90, 64]
print(f"Average score: {average(scores)}")
- Click the “Run Python File” (play) button in the top-right. This just runs
python3 average.pyin the integrated terminal.
Average score: 59.75
But (72 + 85 + 90 + 64) / 4 is 77.75. Our program runs, but it’s wrong. Time to debug!
Part 2: Debugging
What is debugging?
A bug is any case where a program behaves differently to how we intended. It may crash, give the wrong answer or just hang.
Debugging is finding out why your program isn’t working and fixing it. The hard part is rarely the fix but rather finding where the program’s behaviour changes from what you expected. Debugging tools let you see what your program is actually doing, rather than what you think it’s doing.
(Fun fact: in 1947, Grace Hopper’s team found an actual moth in a relay of the Harvard Mark II and taped it into their logbook as the “first actual case of bug being found”. The joke was that engineers already called faults “bugs”.)
Debugging with Print Statements
One of the simplest methods to debug a program is to add print statements, printing values or logging that a certain point in the code has been reached.
Let’s take our previous broken python code:
def average(numbers):
total = 0
for i in range(1, len(numbers)):
total += numbers[i]
print(total)
return total / len(numbers)
scores = [72, 85, 90, 64]
print(f"Average score: {average(scores)}")
Here the line print(total) has been added so we can keep track of the value of total.
our output:
85
175
239
Average score: 59.75
From this our error is pretty clear! Total should start at 72, not 85. All we have to do is find what caused it to be 85 first, and we can see its because of i starting at 1.
There are downsides to this method however!
- We are required to have the source code
- We have to guess in advance what to print, then edit and rerun each time (spotting the variable like total may not be so simple in larger programs!)
- The print statements may change program optimisations, altering any undefined behaviour/edge cases (the print command can slow down your program alot!)
A debugger solves this: it lets you pause a running program, inspect its state, and step through it line by line, without modifying the code.
Debugging in VS Code
VS Code’s debugger drives a language-specific debugger underneath: debugpy for Python, and gdb or lldb for C/C++. So the VS Code debugger for C is literally driving the same gdb we’ll use in the shell later on.
- Breakpoint: click in the gutter left of a line number (or press
F9) to pause just before that line runs. A red dot should appear - Variables / Watch: see all variables, or track specific expressions, at the current point.
- Call Stack: which function called which to get here.
- Debug Console: evaluate expressions (or change variables) in the paused program.
- Conditional breakpoints and logpoints (right-click the gutter): pause only when e.g.
i == 500, or print a message without pausing or editing your code.
| Action | Shortcut |
|---|---|
| Start / Continue | F5 |
| Step Over | F10 |
| Step Into | F11 |
| Step Out | shift+F11 |
| Stop | shift+F5 |
For arguments, environment variables, or debugging tests/servers, create a .vscode/launch.json from the Run and Debug view.
Demo - debugging average.py
- Set a breakpoint on
total += numbers[i]and pressF5. - In the Variables view,
iis1. Addnumbers[i]to Watch: it’s85, but the first score is72! - Press
F5a few times:igoes1, 2, 3, never0. - Fix by ensuring i starts of as 0, and rerun to get the correct result.
Demo - debugging with the call stack
Here is the code of discountshopping.py
def apply_discount(price, discount_code):
discounts = {"STUDENT": 0.10, "XMAS": 0.25}
rate = discounts[discount_code]
return price * (1 - rate)
def item_total(item):
subtotal = item["price"] * item["quantity"]
return apply_discount(subtotal, item["code"])
def order_total(order):
total = 0
for item in order:
total += item_total(item)
return total
basket = [
{"name": "Keyboard", "price": 50, "quantity": 1, "code": "STUDENT"},
{"name": "Mouse", "price": 20, "quantity": 2, "code": "XMAS"},
{"name": "Monitor", "price": 150, "quantity": 1, "code": "xmas"},
]
print(f"Order total: {order_total(basket)}")
Running this file throws errors
total += item_total(item)
~~~~~~~~~~^^^^^^
File "callstack.py", line 9, in item_total
return apply_discount(subtotal, item["code"])
File "callstack.py", line 3, in apply_discount
rate = discounts[discount_code]
However, this does not make what the error is very obvious.
We could use the above methods such as breakpoints + variable watch, however as we have many functions being used, this may be too confusing / time consuming. Instead, we can view the call stack in the debugger.
Debugging outside the IDE: gdb
Sometimes you don’t have an IDE: you’re SSH’d into a server, or debugging a binary without its source. For C/C++ on Linux, the classic tool is gdb (the GNU Debugger), a powerful and free debugger that lets you explore and modify programs during runtime. Everything we just did in VS Code, you can do in gdb.
Intro and Setup
Debuggers like gdb use symbol tables in executables, which catalogue functions, variables and their scopes.
gdb can be installed with your package manager, e.g. apt install gdb (on macOS, use lldb, which works similarly).
Configuration can be stored in ~/.gdbinit. Useful settings include set disassembly-flavor intel (more readable assembly) and set print asm-demangle on (readable C++ function names). Plugins such as peda, gef and pwndbg are also loaded from here (see Plugins).
Debugging your own program
Compile with debug symbols (-g) and optimisation disabled (-O0):
g++ -g -O0 main.cpp -o main
-gkeeps function/variable names and line numbers in the program. It is not on by default, and-sstrips symbols entirely (useful for smaller production builds).-O0stops the compiler rearranging your code, so what runs matches what you wrote.
Demos
Demo 1 - basic debugging
#include <iostream>
#include <stdlib.h> //srand
#include <stdio.h> //printf
using namespace std;
int main () {
srand (time(NULL));
int alpha = rand() % 8;
cout << "Hello world." << endl;
int beta = 2;
printf("alpha is set to is %s\n", alpha);
printf("kiwi is set to is %s\n", beta);
return 0;
}
We compile with g++ main.cpp -g -O0 -o main and run it. Sadly, we get a segmentation fault :(
Run gdb main to get a (gdb) prompt, then type run:
Program received signal SIGSEGV, Segmentation fault.
__strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:74
../sysdeps/x86_64/multiarch/strlen-avx2.S: No such file or directory.
We get the signal (SIGSEGV, a segmentation fault) and where it stopped, but that’s deep inside the C standard library, not our code. backtrace (or bt) shows the full chain of calls:
#0 __strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:74
#1 0x00007f59aee0ed31 in __vfprintf_internal (s=0x7f59aefb3780
<_IO_2_1_stdout_>, format=0x55ab53463011 "alpha is set to is %s\n",
ap=ap@entry=0x7ffe8e60e700, mode_flags=mode_flags@entry=0) at
./stdio-common/vfprintf-internal.c:1517
#2 0x00007f59aedf879f in __printf (format=<optimized out>) at
./stdio-common/printf.c:33
#3 0x000055ab534622a4 in main () at main.cpp:15
Frame #3 shows the crash came from line 15 of main.cpp. There, %s expects a pointer to a string, but we passed an int, so printf reads from an invalid address. Changing %s to %d fixes it. This is the same as VS Code’s Call Stack view, in text form.
Demo 2 - changing values
gdb lets us inspect and change variables while the program runs:
#include <iostream>
using namespace std;
int main () {
volatile int decider = 1;
if (decider == 1){
cout << "you lose" << endl;
} else {
cout << "you win" << endl;
}
return 0;
}
Break on main, run, and step over the assignment:
(gdb) b main
Breakpoint 1 at 0x1151: file main.cpp, line 7.
(gdb) r
Breakpoint 1, main () at main.cpp:7
7 volatile int decider = 1;
(gdb) s
8 if (decider == 1){
(gdb) print decider
$1 = 1
Ah! Panic! If decider is 1, we’ll lose! Let’s change that:
(gdb) set var decider = 2
(gdb) s
11 cout << "you win" << endl;
Printing variables
To print the values of all variables you can use:
info locals
or to print the value of one specific variable
print <variable name>
p <variable name>
Attaching gdb to running processes
Sometimes you may have processes running that might be bugging out, in which case you may want to use gdb instead of restarting the process to try replicate the error!
To attach gdb to a running process (elevated privileges may be required!)
gdp -p <pid>
or from within gdb
(gdb) attach <pid>
(Get pid by using the ps command which was covered in advanced shell!)
DEMO
#include <stdio.h>
#include <unistd.h>
int main () {
int counter = 0;
while (1) {
counter++;
printf("counter: %d\n", counter);
sleep(1);
}
return 0;
}
This is a simple program that will increment a counter once per second.
- Ctrl + Z to pause and put in the background.
- Run
psto list your processes and copy the PID of the process. - Run
fgto bring the counter process back. - Run one of the above commands (may require sudo) in a new terminal with the PID you got and you should be attached!
Once attached, it’s helpful to run the bt or backtrace command.
bt
#0 0x00007f04b6e1fc5b in clock_nanosleep@GLIBC_2.2.5 () from /lib64/libc.so.6
#1 0x00007f04b6e2bf77 in nanosleep () from /lib64/libc.so.6
#2 0x00007f04b6e3e75e in sleep () from /lib64/libc.so.6
#3 0x0000000000401177 in main () at attachdemo.cpp:11
This shows the current call stack just like we did in VS code! From here we can see that our main function that we have attached to is #3, so to switch to it we can do:
frame 3
and we will now be “inside” our attached process and we can debug!
To detach:
detach
Plugins
gdb is even better with a plugin. Install one of these (they each add themselves to ~/.gdbinit and conflict with each other). They add a context view of registers, assembly and the stack, plus commands like checksec. As with VS Code extensions, stick to well-known projects.
peda:
$ git clone https://github.com/longld/peda.git ~/peda
$ echo "source ~/peda/peda.py" >> ~/.gdbinit
gef:
$ wget -O ~/.gdbinit-gef.py -q https://gef.blah.cat/py
$ echo source ~/.gdbinit-gef.py >> ~/.gdbinit
pwndbg:
$ git clone https://github.com/pwndbg/pwndbg
$ cd pwndbg
$ ./setup.sh
Part 3: A Little Bit of Profiling
So with debugging we can fix our broken code, but what if it’s running correctly but just taking a long time to run? (when realistically it shouldn’t) With profiling methods we can actually measure where all of our time is being spent!
Timing
The shell’s time command times a whole program:
$ time python3 profile_demo.py
real 0m0.71s
user 0m0.20s
sys 0m0.01s
real is wall-clock time; user and sys are CPU time in your code, user being time spent executing code in user mode, and sys being executing kernel code on behalf of your program. If real is much bigger than user + sys, your program is mostly waiting (on the network, disk, etc.), not computing.
This command can be really useful in actually benchmarking any optimisations you make! (The goal is to make time go down)
Easy to see the difference when running a command like:
time sleep 3
real: ~ 3 seconds because thats how long the program should run for.
user: Almost 0 because CPU did no meaningful computations.
sys: Also almost 0 because very little kernel processing would be needed.
Profilers
A profiler tells you where the time goes. Python ships with cProfile:
import time
def fetch_data():
time.sleep(0.5) # pretend this is a slow network call
return list(range(1000))
def slow_sum(n):
total = 0
for i in range(n):
total += i
return total
def fast_sum(n):
return n * (n - 1) // 2
def main():
data = fetch_data()
print(slow_sum(5_000_000))
print(fast_sum(5_000_000))
main()
$ python3 -m cProfile -s cumtime profile_demo.py
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.697 0.697 profile_demo.py:16(main)
1 0.000 0.000 0.500 0.500 profile_demo.py:3(fetch_data)
1 0.500 0.500 0.500 0.500 {built-in method time.sleep}
1 0.197 0.197 0.197 0.197 profile_demo.py:7(slow_sum)
1 0.000 0.000 0.000 0.000 profile_demo.py:13(fast_sum)
tottime is time in the function itself; cumtime includes everything it calls. Most of the time is spent waiting in fetch_data, and slow_sum takes ~0.2s while fast_sum computes the same answer instantly.
You should also notice that the cumtime of main is the sum of time taken for fetch data + slow_sum!
Other tools worth knowing:
- C/C++:
perf(perf record ./prog, thenperf report),valgrind --tool=callgrind, andgprof. - Rust Profililng:
perfandheaptrack - Memory:
valgrindfinds leaks and invalid memory accesses in C/C++; Python hastracemalloc. - Visualising:
snakeviz(Python) and flame graphs make large profiles readable.
Conclusion
IDEs are a personal choice: you may like a heavier, full-featured IDE, or a lightweight one that stays out of your way, and you might use one for everything or switch per project. Play around, find what works for you, and find your productivity spike! (Hopefully. Missing Semester makes no guarantees of an improvement in productivity.)
Whatever you use, the debugging and profiling concepts are the same everywhere: breakpoints, stepping, inspecting state, call stacks, and measuring before optimising. Learn them once, and you can use gdb, pdb, or any other debugger you come across.
Licensed under CC BY-NC-SA.