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 attempts to preserve whitespace and comments in nested functions
and each function name contains the line number from the source file to make
debugging easier. 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 <stdio.h>
#define NESTED_FUNCTION_NAME nested_function_src_main
#include "my_nested_functions.c"
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
static int nested_function_src_main_line_7(int a, int b) {
return a + b; // Add two numbers.
}
#endif // NESTED_FUNCTIONS_SRC_MAINMIT