Where the C macros stored in memory and how does it consumes more memory compared to functions?

后端 未结 4 1047
孤城傲影
孤城傲影 2021-01-22 11:05

I searched in web where will be the C macros stored in memory and how does it consumes more memory compared to functions? Could not get any satisfying answer .Can anyone please

相关标签:
4条回答
  • 2021-01-22 11:07

    Macros are a preprocessor construct. All macros are replaced by their definitions before the compiler even sees the code.

    This means that if you use a lot of macros with large replacements, they will generate a lot code. Function calls don't work that way, since they call a single function that only has the code once.

    There is no standard way of figuring out how much code is due to macros, no.

    0 讨论(0)
  • 2021-01-22 11:24

    Macros are not stored in memory anywhere in the final program but instead the code for the macro is repeated whenever it occurs. As far as the actual compiler is concerned they don't even exist, they've been replaced by the preprocessor before they get that far.

    The reason that this usually takes up more memory is that it gets repeated every time the macro is used. There's no general way to determine how much memory they will take up but, honestly, memory considerations are really not the reason the reason to prefer functions to macros.

    If you having a burning need to find out the amount of memory consumed you could approximate it by looking at the disassembly of a place where you use the macro and multiplying the number of times that the macro appears in the source code by the number of lines of disassembly produced. However, there's no guarantee that different uses of the macro or the same use under different circumstances will produce identical code so this can only ever be a crude measure.

    0 讨论(0)
  • 2021-01-22 11:28

    "The reason that this usually takes up more memory is that it gets repeated every time the macro is used."

    With a modern compiler depending on the compile settings (FAST CODE/SMALL CODE) it may spot commonly used code and optimize it into a function (SMALL), or it may inline the code for speed (FAST).

    It isn't always the case that the code will always be bigger depends on how good your optimizer is and the compiler settings you use.

    Of course you could always use macros that call functions rather than contain large inline sections of code. That is totally down to your choice.

    0 讨论(0)
  • 2021-01-22 11:29

    The values of C macros aren't stored in memory during program execution. Their values are instead copied over to wherever they're used during compilation.

    0 讨论(0)
提交回复
热议问题