C language global variable multi-File Usage

Source: Internet
Author: User

Defines a global variable and wants to use it in multiple files,CodeAs follows:

 
// Var. hextern int var; // var. C # include "var. H "int Var = 10; // othera. C # include "var. H "// otherb. C # include "var. H "// otherc. C # include "var. h"

Only initial values can be assigned to one file; otherwise, the link fails.

See the question C:

Can global variables be defined in multiple. C? Why?

The above is not acceptable, but you can add static in front of it. Static is the static global variable, which is only used in this module.

Global Variables(External variables)The descriptionStatic
It constitutes a static global variable. The global variable itself is a static storage method,
Static global variables are also static storage methods.
The two are not different in storage methods. The difference between the two lies in that the scope of non-static global variables is the whole source.Program,
When a source program is composed of multiple source files, non-static global variables are valid in each source file.
The static global variable limits its scope, that is, it is valid only in the source file that defines the variable,
It cannot be used in other source files of the same source program. Because the scope of static global variables is limited to one source file, they can only be shared by functions in the source file,
Therefore, you can avoid errors in other source files.

After a local variable is changed to a static variable, its storage mode is changed, that is, its lifetime is changed. After changing a global variable to a static variable, it changes its scope,
Limits its scope of use.

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.