Solve the problem of multiple definition of in C/C ++-C ++ Language Program Development Technical Article _ c ++ programming-

Source: Internet
Author: User

Solve the problem of multiple definition of in C/C ++-C ++ Language Program Development Technical Article _ c ++ programming-

Solve the problem of multiple definition of in C/C ++
15:06:17 let me say something
FavoritesI want to contribute

main. cpp
# include "Global. H"

int main (...)
{< br>...
}

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.

an error occurs during compilation:
first defined here
multiple definition of

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

solution:

Method 1:
in global. C (or. CPP), and then the header file global. h add extern before all variable declarations.
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:
. h: Add macro judgment symbols that prevent repeated definitions
your. add Conditional compilation in H
# ifndef global
# define global
XXXXX
# endif
remember: ifndef must be in the first line without any comments or statements on 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.