This script allows you to write NESTED_FUNCTION macros in standard C programs
without depending on compiler extensions. It is intended to be run as a
preprocessing step before compilation. It generates a separate file that you
can include in your project which defines all the nested functions.
The generated file also defines the NESTED_FUNCTION macro. The macro discards
the function body and replaces it with a function pointer to one of the
functions in the generated file. You must #define NESTED_FUNCTION_NAME at the
top of each source file so that the functions can be uniquely identified.
The script preserves the original whitespace and comments in nested functions,
and emits #line directives so that compiler errors refer to the source location.
The generated file also includes header guards, and the script will print a
warning to stderr if NESTED_FUNCTION_NAME is not defined.
Note that nested functions are not lambdas. They do not capture enclosing
scope so you must provide any context that is needed via function arguments.
This preprocessor script is MIT licensed, authored by Chris Patuzzo, 2026.
Example usage:
#include "my_nested_functions.c"
#include <stdio.h>
#define NESTED_FUNCTION_NAME nested_function_src_main
int main(void) {
void *fn = NESTED_FUNCTION(int, (int a, int b), {
return a + b; // Add two numbers.
});
int (*sum)(int, int) = fn;
printf("The sum is %d.\n", sum(3, 4));
}Example of running the script:
chmod a+x extract_nested_functions.c && ./extract_nested_functions.c src/* > src/my_nested_functions.c && cc src/main.c && ./a.out
The sum is 7.Example of generated file:
// This file was generated by the extract_nested_functions.c script.
#ifndef NESTED_FUNCTIONS_SRC_MAIN
#define NESTED_FUNCTIONS_SRC_MAIN
#ifndef NESTED_FUNCTION
#define __NESTED_FUNCTION_CONCAT(a, b, c) a##b##c
#define _NESTED_FUNCTION_CONCAT(a, b, c) __NESTED_FUNCTION_CONCAT(a, b, c)
#define NESTED_FUNCTION(return_type, params, ...) _NESTED_FUNCTION_CONCAT(NESTED_FUNCTION_NAME, _line_, __LINE__)
#endif // NESTED_FUNCTION
#line 7 "src/main.c"
static int nested_function_src_main_line_9(int a, int b) {
#line 8 "src/main.c"
return a + b; // Add two numbers.
}
#endif // NESTED_FUNCTIONS_SRC_MAINNote that "line_9" refers to the closing line of the nested function. You
should use the same compiler for running the preprocessor and compiling your
program to avoid any differences in how the __LINE__ macro is evaluated.
MIT