title: How to determine maximum stack usage in embedded system with gcc?
body: <p>I'm writing the startup code for an embedded system -- the code that loads the initial stack pointer before jumping to the main() function -- and I need to tell it how many bytes of stack my application will use (or some larger, conservative estimate).</p>
  <p>I've been told the gcc compiler now has a -fstack-usage option and -fcallgraph-info option that can somehow be used to statically calculates the exact &quot;Maximum Stack Usage&quot; for me.
  ( <a href="https://www.adacore.com/uploads/technical-papers/Stack_Analysis.pdf" rel="nofollow noreferrer">&quot;Compile-time stack requirements analysis with GCC&quot;</a> by Botcazou, Comar, and Hainque ).</p>
  <p>Nigel Jones says that recursion is a really bad idea in embedded systems (<a href="https://embeddedgurus.com/stack-overflow/2009/03/computing-your-stack-size/" rel="nofollow noreferrer">&quot;Computing your stack size&quot;</a> 2009), so I've been careful not to make any mutually recursive functions in this code.</p>
  <p>Also, I make sure that none of my interrupt handlers ever re-enable interrupts until their final return-from-interrupt instruction, so I don't need to worry about re-entrant interrupt handlers.</p>
  <p>Without recursion or re-entrant interrupt handlers, it should possible to statically determine the maximum stack usage. (And so most of the answers to <a href="https://stackoverflow.com/questions/389219/how-to-determine-maximum-stack-usage">How to determine maximum stack usage?</a> do not apply).
  My understanding is I (or preferably, some bit of code on my PC that is automatically run every time I rebuild the executable) first find the maximum stack depth for each interrupt handler when it's not interrupted by a higher-priority interrupt, and the maximum stack depth of the main() function when it is not interrupted.
  Then I add them all up to find the total (worst-case) maximum stack depth. That occurs (in my embedded system) when the main() background task is at its maximum depth when it is interrupted by the lowest-priority interrupt, and that interrupt is at its maximum depth when it is interrupted by the next-lowest-priority interrupt, and so on.</p>
  <p>I'm using YAGARTO with gcc 4.6.0 to compile code for the LM3S1968 ARM Cortex-M3.</p>
  <p>So how do I use the -fstack-usage option and -fcallgraph-info option with gcc to calculate the maximum stack depth? Or is there some better approach to determine maximum stack usage?</p>
  <p>(See <a href="https://stackoverflow.com/questions/6375762/how-to-determine-maximum-stack-usage-in-embedded-system">How to determine maximum stack usage in embedded system?</a> for almost the same question targeted to the Keil compiler .)</p>