Definition and declaration of C language variables

Source: Internet
Author: User

A low-level error has been made today, where a variable is defined in the header file, and the header file is called by multiple source files, causing the variable to be defined repeatedly. Then I changed the amount of change to static type, this compilation is not wrong, that is, the result is not the same as I imagined, changed in one file, and in the case of another file, the result is 0.

Then find that the error is very low-level, the correct usage is defined in the source file, declared in the header file, and other source files to use, reference the header file.

Let's say the relationship between definition and declaration:

Definition: There is such a thing, and it is placed here.

Statement: It refers only to something that is defined in another file.

So the definition can only be once, and the declaration is multiple times, when the compiler compiles, only the variables defined by the file generated by the intermediate file will have the information of the variable, and other declarations of the variable in the file, there will be no such variable.

In fact, there is a question left, why the static modifier variable in the header file will not report a duplicate definition of the error?

This is because each of the source files that contain the header file has a variable of their own, note that although it is defined only once in the header file, the actual result is that each source file containing the header defines a variable of the same name, but how many of the source files are referenced, and how many variables are defined. And each source file can only access variables that belong to it (because it is static).

Definition and declaration of C language variables

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.