6 years, 5 months ago.

Why global variables are used heavily in tutorials?

I think I'm kind of seasoned C++ programmer, and through the years I've noticed that global variables are the evil if not used with caution.

While skiming through the mbed tutorials I've seen that global variables are used heavily, even when that feature is not need it. Encapsulation and data hidding are lost when every variable are defined in the global scope.

Of course, whenever there exist a shared resource then the easiest way to share it is defining it in the global space. Otherwise it's a non-sense to have global variables in our programs.

I guess this style of programming has been imported from the Arduino platform. However, the mbed masters programmers shouldn't use them as free as they are using it right now in the hope of clean, neat and safe programming. That's way mbed is using C++, I bet.

1 Answer

6 years, 5 months ago.

Hi Xavier,

In order to keep the Mbed OS examples short and concise, we use global variables. Also, since many of the code examples for Mbed OS exist on API documentation pages (for example: https://os.mbed.com/docs/latest/reference/serial.html#serial-examples) the primary purpose of these short examples are to demonstrate how to use that Mbed OS API and its use cases.

Of course, experienced programmers are encouraged to use professional coding standards and practices in their programs. Our Mbed OS coding style guide and practices can be viewed here:

Please let me know if you have any questions!

- Jenny, team Mbed

If this solved your question, please make sure to click the "Thanks" link below!

I do understand the point. With good programming practices the C++ language becomes an unbeatable beast. However, with bad practices, all that power is lost. Don't missunderstand me, I think the mbed platform is awesome, but many people that is introduced to embedded programing in C/C++ should avoid the use of global variables, until they understand when and why variables in the global space are good (or the only option). Meanwhile this people should stick to local variables and passing data through the function's argument list.

For example, I can't see what is the problem if led1 and led2 would have been declared as local variables in the next code (taken from https://os.mbed.com/docs/v5.9/tutorials/application-flow-control.html#thread):

DigitalOut led1(LED1); DigitalOut led2(LED2);

void led2_thread(void const *args) { while (true) { led2 = !led2; Thread::wait(1000); } }

int main() { Thread thread(led2_thread); while (true) { led1 = !led1; Thread::wait(500); } }

Are led1 and led2 really need in the global space?

With or without global variables people write awesome applications, but if they were tought good programming practices from the begining, then all the C++ power will be taken out. By the way, I'm a C++ crazy fan :)

posted by Xavier Rguez 20 Jun 2018