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 all contain header file state.h.

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

1, declare the global variable in state.h: extern int A;

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

This allows other source files to use the variable.

What is required here is "declaration", not "definition". According to the C + + standard, a variable declaration must satisfy two conditions, otherwise it is defined as:
(1) 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 a global variable (undefined), if the variable has multiple files, you can create a new CPP, define it, and add the CPP to the project. Header file Please do not define any variables, it 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 multiple CPP, it can cause a duplicate-defined link error.

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

If a 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 (. h files are not compiled), only contains the compilation in each of its included CPP files, which is equivalent to using the static definition in. cpp.
Reproduced from: http://blog.sina.com.cn/s/blog_74a459380101rjh4.html

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.