Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much memory space does Macro definition takes?

Tags:

c

macros

I have a lot of unused macros in my code. So, I am wondering.. If a macro is unused, does it takes up memory space in your program?

The type of macros I have are just the basic ones. Example:

#define TEST_ID 0
like image 524
chris yo Avatar asked Jul 31 '14 07:07

chris yo


People also ask

Do macros take up a lot of space?

Because macros are directly substituted into the program by the preprocessor, they inevitably use more memory space than an equivalently defined function.

Does #define take up memory?

#define is a useful C++ component that allows the programmer to give a name to a constant value before the program is compiled. Defined constants in arduino don't take up any program memory space on the chip.

Where macros are stored in memory?

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.

Where is #define stored?

Typically, #defines which are shared between multiple files are stored in a header file (*. h) which is included in each source file that requires the #define.


3 Answers

Macros will be expanded during preprocessing phase so they don't exist in your program. They just take some space in your source code.

Edit:

In response to Barmar's comment, I did some research.

MSVC 2012: In debug build (when all optimizations are disabled, /Od), adding lines of macros won't cause the growth of the size of your program.

GCC: does provide a way to include macro in debugging information as long as you compile your program with a specific flag. See here. (I didn't know that before myself. Thank you, @Barmar, @Sydius)

like image 62
Eric Z Avatar answered Sep 28 '22 17:09

Eric Z


No, doesn't takes space until is used, for this two pieces of code:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("%d %s\n", argc, argv[0]);
    return 0;
}

and

#include <stdio.h>

#define TEST_ID 0

int main(int argc, char *argv[])
{
    printf("%d %s\n", argc, argv[0]);
    return 0;
}

The ASM generated with gcc -S is the same.

like image 26
David Ranieri Avatar answered Sep 28 '22 16:09

David Ranieri


macro is replaced by preprocessor before compilng start. if you define a macro, and doesn't use it, the compiler will never see it.

like image 44
4simplicity Avatar answered Sep 28 '22 18:09

4simplicity