Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C memory space and #defines

I am working on an embedded system, so memory is precious for me.

One issue that has been recurring is that I've been running out of memory space when attempting to compile a program for it. This is usually fixed by limiting the number of typedefs, etc that can take up a lot of space.

There is a macro generator that I use to create a file with a lot of #define's in it. Some of these are simple values, others are boundary checks

ie

#define SIGNAL1 (float)0.03f
#define SIGNAL1_ISVALID(value) ((value >= 0.0f) && (value <= 10.0f))

Now, I don't use all of these defines. I use some, but not actually the majority. I have been told that they don't actually take up any memory if they are not used, but I was unsure on this point. I'm hoping that by cutting out the unused ones that I can free up some extra memory (but again, I was told this is pointless).

Do unused #define's take up any memory space?

like image 617
the_e Avatar asked Aug 28 '09 07:08

the_e


People also ask

How is memory stored in C?

When a program in C is executed, binary code is loaded into RAM and is segregated into five different areas which are text segment, initialized data segment, uninitialized data segment, command-line arguments, stack, and heap. Code instructions are stored in text segment and this is shareable memory.

What is memory layout in C?

Basically, the memory layout of C program contains five segments these are the stack segment, heap segment, BSS (block started by symbol), DS (Data Segment) and text segment. Each segment has own read, write and executable permission.

Do #defines use memory?

Description. #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.

How memory is allocated for variables in C?

When a variable is declared compiler automatically allocates memory for it. This is known as compile time memory allocation or static memory allocation. Memory can be allocated for data variables after the program begins execution. This mechanism is known as runtime memory allocation or dynamic memory allocation.


1 Answers

No, #defines take up no space unless they are used - #defines work like find/replace; whenever the compiler sees the left half, it'll replace it with the right half before it actually compiles.

So, if you have:

float f = SIGNAL1;

The compiler will literally interpret the statement:

float f = (float)0.03f;

It will never see the SIGNAL1, it won't show up in a debugger, etc.

like image 168
Ana Betts Avatar answered Nov 15 '22 10:11

Ana Betts