ahmad
ahmad

Reputation: 73

How would having an #include file.h inside a function work?

I am working on an embedded systems project, so i am dealing with limited memory. I have this huge array of strings in C, it is basically an array of 31 bitmaps. I have it in a separate file called images.c and the header file is images.h, when i include it in main.c file it would take a huge chunk of memory. My question is, if i include the file inside a function and would that array take memory when the function is called? for example

#include <stdio>

void foo(){
   #include "images.h"
   // do stuff with the array of bitmaps
}

int main(){
   //logic to sometimes call foo 
}

would this work? will the array be a local variable in the function and its memory location would be cleared once the function is terminated?

Also am I understanding this correct? I understand that local variables are only local to the scope they are in and cannot be called outside it, but memory wise, is their location in memory actually cleared up? as if they were never there? similar to how a garbage collector works?

Upvotes: 0

Views: 67

Answers (1)

Barmar
Barmar

Reputation: 782167

As far as #include goes, it's a simple substitution of the header file into the C file at compile time. It's no different from pasting the file contents directly into the C file. It has no effect on memory allocation.

Regarding the resulting memory use, in typical implementations:

When the process starts, the initialization data will be part of the text segment of the process. This is usually memory mapped to the executable file, just like the program code, so there's little overhead at that time.

When the function is called, this initialization data will be copied into the stack. So the relevant portion of the file will be paged into RAM, then code similar to memcpy() will copy it to the stack variable.

When the function returns, the stack is unwound.

Putting large arrays in local variables is generally not recommended. The size of the stack segment is usually much more limited than the data segment, where global variables and dynamically-allocated memory are stored. See for example C programming, why does this large array declaration produce a segmentation fault?.

Declaring the array locally might be reasonable if the function is unlikely to be called. But if the function is called repeatedly, it would probably be better to just declare the array as a global, so it only has to be copied into memory once when the program starts. And if it's constant, it will be put into the text segment just like initialization data, and accessing it will simply reference that same memory.

Upvotes: 1

Related Questions