C + + multiple source files share a global variable (extern usage)

Source: Internet
Author: User

Example:

Header file: state.h source file: State.cpp

Other source files: T1.cpp t2.cpp t3.cpp, these source files contain header file state.h.

You need to define a global variable for use in these source files:

1. Declare global variables in state.h: extern int A;

2. Define the global variable in state.cpp: int a = 10;

This allows the variable to be used by other source files.

What is needed here is "declaration", not "definition"! According to the C + + standard, a variable declaration must satisfy two conditions at the same time, otherwise it is defined as:
(1) The declaration must use the extern keyword; (2) cannot assign an initial value to a variable
extern int A; Statement


int A; Defined

int a = 0; Defined

extern int a = 0; Defined

The header file should use the extern keyword to declare the global variable (not defined), if the variable has more than one file to use, you can create a new CPP, defined in it, the CPP into the project. header file Please do not define any variables, that is very amateur behavior ...

Generally stated in the header file, with extern, defined in CPP. If defined in the header file, if the header file is referenced by more than one CPP, it causes a duplicate-defined link error.

Header files can only declare global variables (extern), not defined (deprecated). cpp, in the outermost definition (int gi), direct reference

If the static definition is used in. cpp, the variable is valid only in the current CPP file and is not valid in another file
Using the static definition in. h does not compile (the. h file does not compile) and only contains the compilation in the CPP file for each of its include, which is equivalent to using the static definition in. cpp.

C + + multiple source files share a global variable (extern usage)

Related Article

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.