Implementation of GCC's Nested Functions (vs. C++ Lambdas)
Martin Uecker, 2026-09-05
Introduction
Here, I want to explain how GCC's nested function are implemented. I am not going to discuss taking the address of a nested function that may require the creation of a trampoline. We discussed this topic - and how to get around it - already in several previous blog posts. Instead, I want to describe the basic mechanism that is used to access variables of a parent function.
Nested Functions
Let us start with a very simple example.
int foo(int k) { int bar(int x) { return x + 1; } return bar(k); }
Here, the nested function does not access any variable of the parent function. In this case, it can simply be lifted out of the parent function and be compiled as a separate function. Such functions can still can be useful to define small helper functions, or when locally defining a type that can then be used in the nested function. WG14 is currently considering proposal N3884 that would allow such non-capturing local functions when defined with the static storage class.
But let's consider an example where a nested function accesses a variable of the parent function.
... continue reading