开发者

How do I measure the total size of my global variables?

开发者 https://www.devze.com 2022-12-21 02:42 出处:网络
I\'m creating a c program that I intend to run on an ARM processor in the near timeframe. I want to measure the amount of memory I\'m u开发者_高级运维sing with my global variables while ignoring the s

I'm creating a c program that I intend to run on an ARM processor in the near timeframe. I want to measure the amount of memory I'm u开发者_高级运维sing with my global variables while ignoring the size of the stack/heap. Is there a way to either get gcc to dump this out at compile time or to retrieve this information from the compiled binary?


A great way to see where your memory is going is to look at the linker map. A linker map is a file that is generated by the linker and details all memory locations for the program. You can see memory allocation on a symbol by symbol basis for global variables as well as code. I've used linker maps in the past for projects which have tight memory requirements. They make it easy to identify problems areas like global memory buffers which take up alot of space.

Add this option to the gcc command line to generate the linker map:

-Wl,-Map=output.map


The GNU binutils suite contains a program called "size", which is the easiest way to get the data you need -- or, at least, a reasonable approximation. For a typical program (in this case, not a small embedded one), the output might look like:

   text    data     bss     dec     hex filename
 332268    2200   19376  353844   56634 test-directory/add

The first three columns are sizes of the sections in the binary: "text" is the executable code, "data" is constants and so forth -- including ones that represent initial variables with explicit initializers -- and "bss" is initializers for everything that gets implicitly statically initialized. In a typical embedded program, those static initializers are pretty much exclusively for global variables (and, for your purposes, you might want to include the other static variables in your measurement anyway since they're also not on the stack or heap).

Thus, I think that you end up with the sum of "data" and "bss" being essentially what you want. (After reading the article hlovdal linked to, I'm less sure of this than I was; perhaps commenters can add confirmation?)

(After that, "dec" and "hex" are the total size of everything in decimal and hexadecimal, and "filename" is of course obvious.)


You need to analyse the different memory segments with objdump. See here for an article and here for another answer which gives some details on this.

0

精彩评论

暂无评论...
验证码 换一张
取 消