Embedded C programming Experience global variables fierce in the tiger

Source: Internet
Author: User
Tags openssl api


/*********************************************************************************

* Filename: The Sound of Research and development: the global variable of embedded C programming experience the Tiger

* author:sedatefire e-mail:[email protected]

* version:1.001 time:2012-01-05

* Key: Embedded os-less global variable single chip microcomputer

**********************************************************************************/

work has been a few years, from a technical newcomer to the now self-styled calf-level characters, but also to find their own information to read. On the forum, in the bookstore, in the magazine ... Want to be some rookie shallow self-dazzling virgin paste, want to be strategically advantageous position cloud in the fog to go to the concept of the article, finally met a practice-type master writing articles, but in the occasion of the moment to a halt. This is ineffective, after reading the heart is a knot unceasingly. Well, today and strong back to Daniel, caught dead talk about the problem of global variables in embedded C programming.

Embedded especially monolithic microcomputer os-less program, the most apt error is the global variable flying everywhere. this phenomenon is common in early compilations of transformed programmers and beginners, who almost use global variables as function parameters. In the. h document, define many cluttered structures, extern a bunch of scalp-tingling global variables, and then assign a value of 123 inside the module, which determines what the 123 branch decides to do. Whenever I see this kind of procedure, I always have to face the face and then pat the table thundered. Yes, that's thundered. I do not deny the importance of global variables, but I think it is very prudent to use it, and the misuse of global variables can lead to other more serious structural system problems.

Crossing, and listen to me carefully.

1. It will cause unnecessary constants to be used frequently, especially when this constant is not defined by the macro "justify", the code will be very difficult to read.

2. It can lead to unreasonable software layering, the global variable is equivalent to a shortcut channel, it is easy to make the programmer blurred the "device layer" and "application layer" between the boundary. the underlying program that is written is apt to focus on the application of the upper layer. This software system in the early days of the construction is indeed very efficient , functional debugging progress rapid, but to the late often bug a heap , everywhere "patch", mined area all over. It is not too hard to say that it is a difficult one.

3. Due to the unreasonable layered software , to the post-maintenance , even if only to increase the modification of the deletion of small functions, often from top to bottom excavation three feet to modify , involving most modules, and the original code comments forgot to update the changes , this time, the system to the later maintainer will become more and more like a "mire", the only function of the note is to add some Miyan miasma above the mire.

4. Global variables are heavily used, and some variables linger between interrupts and the main loop program . This time if mishandled, the system bug is random appearance, irregular, at this point initially showed the characteristics of the terminally ill, no Daniel to the tide, doomed to chronic death.

Needless to say, you have succeeded in getting a malformed system that is in a state of mysterious stability! you look at this machine, the machine is looking at you, silent, the heart is creepy. You're not sure when it's going to crash, and don't know when the next complaint will be justified.

Then, I tell you what the consequences are on the real plane.

1. "The Old man" poised, because the system can not leave him, all the "minefield" only he knows. When there is an urgent bug, only he can handle it. you can not only dismiss him, but also give him a raise.

2. New people see the light dead, whenever the recruitment to maintain the system, in addition to change more bugs, basically one months to leave, to the outside also advertise the company's software quality is bad enough rotten.

3. With the subsequent upgrade of the product, few months without contact with the system's creators will find that many mined areas he himself has forgotten, so every time the product upgrade maintenance cycle more and more long , because the modification of a feature will be a lot of bugs, and press a bug, More bugs will pop up. During this time, more global variables are generated. Finally one day he told the boss, no, no, not enough resources, RAM or flash space is too small, upgrade upgrade.

4. The customer complains unceasingly, after the sale also quickly collapses, the salesman also dared not recommend this product , the market share is getting smaller, the company image is getting worse.

to ask my response, there are only two principles:

1. Can not use global variables as far as possible , I think in addition to the system State and control parameters, communication processing and some need for efficiency of the module, the other basic can rely on reasonable software layering and programming skills to solve.

2. If it is unavoidable to be used, how deep it can hide.

1) If only a. c file is used, it is static to the file, and the structure definition is also collected in the way;

2) If there is only one function, then static into the function;

3) If you want to open out to let people read, then use the function return, this is read-only property;

4) If you have to be raped and assigned, well, I open the function interface to let you pass the parameter assignment; 5) I really have to get the extern rape, and I can strictly control the objects that contain my. h files, rather than putting them in public includes.h.

So, you can see how deeply I feel about global variables. Sadly, I have already turned over all those cases that the old people gave me to maintain. Can you understand, do not let the people behind you oh.

2011-12-29 Sequel

thanks to the small support, recommended this blog post, grateful for the fear of the heart, specifically detailed read the next reply. This topic was first published in the Forum, I found that the reply is still relatively warm, but also very happy to hear different voices. For some users mentioned, if a large number of local variables will be prone to stack overflow problem, but also refers to the concept of the program model. Makes sense So let's add some comments:

1. Global variables are unavoidable , almost every device needs it to record the current state, control the timing, transforms. But try not to pass the parameters, this is very taboo.

2. Try to control the scope of the variable in the module using it , if the other modules to access, open a read or write function interface, strictly control the scope of access. This is how the private property of C + + is done. This is also good for debugging future programs. C language has a version of + +, a big reason is to control its flexibility, to say the idea of object-oriented, C language has long been, can also be achieved.

3. When a module contains more than 3 global variables (including), use the structure to wrap it up. 0 will be returned to 0, save absent-minded.

4. In the function to open a static global variable , the global number group, is not occupy the stack space. just some compilers for large chunks of global arrays are placed in different address areas than general variables. If in Keil C51, because is static compile, stack burst out will alarm, so big can enjoy gallop, pay attention to traffic rules just.

5. monolithic microcomputer os-less system, only the stack does not have the heap usage, those default to the heap allocates the space "the Startup.s", may boldly take the heap space to kill.

6. Program model? How to analyze the abstraction, from which angle to build the model? Very willing to listen to the opinions of netizens. I have always been from two angles to analyze the system , events-state machine migration diagram and Data flow chart, the former analysis of control direction, improve the UI, the latter can know the origin of the system of the loss. These theories, the school "software engineering" textbooks have, we may as well learn from the next. Only those theories, after all, originated from large-scale system software management, sledgehammer kill chickens, or to cut a bit.


1, the message mechanism has been fixed to avoid the global variable cost is efficiency
C + + Class wrapper variables are essentially global variables
When multiple modules are accessed, you have to use the static in class.
In C, the compromise is sealed in a struct.
Then use the pointer to pass the address of the struct variable
So there is no global variable and no efficiency problem with the message mechanism.
The cost is the module coupling degree
I like this way better.


2, in the absence of the operating system, the global variable is not a big problem, as long as your global variables in the interrupt function is not used, then it will not affect the value of your global variables, if a global variable to be in the interrupt inside the change, then set the Flag Bai!!!


3.

A subroutine with the external direct contact less, the better the cohesion, and the outside world, is the global variables and parameters, so the fewer parameters and global variables better, otherwise the program is difficult to maintain, readability is not high. Moreover, the global variable occupies a fixed address, in the function, or local to read it also get outside to find, and in a large point of the program if a large number of global variables will reduce the readability of the program, and occupy a lot of limited space, reduce the speed of operation.

Global variables are sometimes unavoidable and can only be minimized by minimizing global variables. There are three main things I can think of:
1. Pass data or pointers through function parameters. For callback functions, there is usually a parameter that is a custom data pointer that can be used to pass a class pointer or to customize a pointer to a struct.
2. A variable that is used only in one function can be defined as a local static variable (defined inside the function, preceded by a static modifier).
3, define a global variable as a structure, define a global structure variable.


4, the global variable has its existence of the inevitable law, the so-called global variable is not safe argument is unfounded, all the insecurity hidden from the code to write the unreliable, is the human factors and norms loopholes. There are companies that want to reduce global variables that's right, don't use global variables that is very unreliable, and more than one place in system programming requires the use of global variables. In some operating systems, the system-mandated task flags can be used instead of global variables, but this is only a form of deformation of global variables, not global variables. In some systems that do not have an operating system, you must use only global variables. One of the most basic uses of global variables is the ability to use static global variables without using dynamic global variables.
2, if you really want to replace the global variables, there is actually a way, is to use a separate memory driver. This method is actually jewelery, perhaps you feel so reliable, but its reliability is not really high, and very resource-intensive.
Its use is very simple, is to implement 4 functions
(1) Application mark
(2) Read Mark
(3) Change of logo
(4) Delete flag
The application of the logo is guaranteed to use only once
3, the concept of C + + encapsulation is object-oriented, but you have to understand a little C + + is only C expansion, is the advanced implementation of C, so all the functions in C + + can be implemented in C, but the implementation is more complicated, if interested can go to see some C object-oriented books, it teaches you how to implement object-oriented

Read (1) | Comments (0) | Forwards (0) |0

Previous: User space and kernel space communication "Proc File system"

Next: Linux device driver induction summary (iii): 6.poll and SELLCT

Related Popular articles
    • Test123
    • Write security code--be careful with the number of symbols ...
    • Encrypting and decrypting using the OpenSSL API ...
    • Print your own C program for a while ...
    • C + + interface for SQL Relay
    • Linux DHCP Peizhi ROC
    • Soft links to Unix files
    • What does this command mean, I'm new ...
    • What does sed-e "/grep/d" mean ...
    • Who can help me solve Linux 2.6 10 ...
Leave something to the owner! ~~ Comment on the hot topic

Embedded C programming Experience global variables fierce in the tiger

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.