C-language static modifier function to parse _c language in detail

Source: Internet
Author: User
Tags modifier visibility

In C, the literal meaning of static is easy to lead us astray, in fact, it has a role of three.
The first and most important piece of the article: Hide.
When we compile multiple files at the same time, all global variables and functions without a static prefix have global visibility. To understand this sentence, I say for example. We want to compile two source files at the same time, one is A.C and the other is main.c.

Here's what a.c.

Copy Code code as follows:

char a = ' a '; Global variable
void msg ()
{
printf ("hello\n");
}

Here's what main.c.
Copy Code code as follows:

int main (void)
{
extern char A; extern variable must is declared before use
printf ("%c", a);
(void) msg ();
return 0;
}

The results of the program's operation are:
A Hello

you may ask:Why is global variable A and function msg defined in A.C used in MAIN.C? As mentioned earlier, all global variables and functions without a static prefix have global visibility and other source files can be accessed. In this example, a is a global variable, MSG is a function, and neither has a static prefix, so main.c is visible for another source file.

If static is added, the other source files are hidden. For example, add static,main.c to the definition of a and MSG before you can see them. With this feature, you can define a function with the same name and a variable of the same name in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables, and for functions the static function is limited to hidden

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.