Solve the problem of multiple definition of in C/C ++

Source: Internet
Author: User

Main. cpp
# Include "global. h"

Int Main (....)
{
...
}

File_1.cpp
# Include "global. h"
....

File_2.cpp
# Include "global. h"

...

Write all global variables, their initialization values, and function declarations in global. h.

Errors occur during compilation:
First defined here
Multiple definition

The reason is that variables and functions are repeatedly defined when global. h is included for multiple times.

Solution:

Method 1:
Declare the variable (not initialized) in global. c (or. cpp), and add extern before all the variable declarations in the header file global. h.
For example, extern int flag;

The. h file is included in other cpp files that require global variables instead of the. cpp file. The compiler will generate the target file for global. cpp, and then connect to the file when using global variables.

Method 2:
Add macro judgment symbols to global. h to prevent repeated Definitions
Add Conditional compilation to your. H file.
# Ifndef GLOBAL
# Define GLOBAL
XXXXX
XXXXX
# Endif
Remember: ifndef must be in the first line, and there should be no comments or statements in the front.

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.