tdoan:
Hi folks,
I just need to confirm my thought about whether compiler provides some memory management.
In assembly language, we have to manage data on our own (load/read to specific register, memory location). However in higher level language such as C we don’t have to up to.
For example:
int x, y, z;
We would have no control where variables x, y and z are stored right? That mean the compiler does some memory management?
Would the compiler be able to know not to overwrite data of the main program when subroutine and interrupt service routine is called?
Your questions are fundamental programming questions. Need some study. The big picture, for C/C++ programs:
variables declared outside of any function are “static”. They are gloabally available to any function >in the same source code file<. They can be made available to functions in other files using certain C/C++ declarations.
Variables declared inside a function exist until that function returns. So this:
void foo(void) {
int x,y,z;
}
are “local” variables. Local to the function here named foo.
But in this one:
void foo(void) {
static int x,y,z;
}
The variables x,y,z are accessed only by foo() in which they are declared. But being static, these don’t lose their value when foo() exits. This static in a function is rarely used. It’s dangerous if foo() is to be reentrant.
the code
// file alpha.c
int x,y,z;
Has x,y,z declared outside of any function, so they are implicitly static. That is, if you put “static” in front of “int”, above, it makes no difference. These variables are usable by any function in alpha.c.
How to share static file level variables among 2+ files is simple but too much to start into here.
Theses are simple C examples. C++ gets more complex. So get a good C (not C++) book, use a C compiler on a PC to write PC programs to master C. Then switch to microprocessors. After that, dig into C++ which has many different concepts.
Dynamic memory allocation such as the “new” operator in C++, or calling malloc(), should NOT be done on small RAM micros. You’ll soon realize why.