When working with low-level or resource-constrained applications - especially in embedded systems - understanding the stack usage of each function is crucial. Excessive or unexpected stack consumption can lead to bugs, stack overflows, or performance issues. This tutorial explains how to check stack usage per function using gcc or g++ compiler.
Let's say we have a simple C program:
#include <stdio.h>
void test() {
char temp[256];
printf("%s\n", temp);
}
int main() {
test();
return 0;
}
The -fstack-usage
option tells to output the estimated stack size used by each function into a .su
file. To compile and analyze stack usage, run the following command:
gcc -fstack-usage main.c
This generates an additional file a-main.su
. It will contain output like this:
main.c:3:6:test 288 static
main.c:8:5:main 16 static
test
uses 288 bytes of stack (256 bytes fortemp
+ extra for alignment, saved registers, etc.).main
uses 16 bytes.
The format is:
<file>:<line>:<col>:<function> <stack_bytes> <type>
static
- size known at compile time.dynamic
- uses variable-length arrays oralloca
function.
Stack usage may vary depending on optimization level (e.g. -O3
). The -fstack-usage
also works with g++ when compiling C++ code.
Leave a Comment
Cancel reply