Declaration and definition of C + + global variables __c++

Source: Internet
Author: User

1. Declare global variables in Header1.h, header1.cpp define global variables

Header1.h
#ifndef header1_h_
#define HEADER1_H_

extern int g_n;//header file must have extern declaration global variable, no value
//int g_ o; error
//int g_o = 10; error
//extern int g_o; error

#endif

 

Header1.cpp
#include "header1.h"

int g_n = 100;//definition can never be added extern, do not give G_n assignment is automatically assigned 0//int the g_n;//
is also correct, g_ N is 0

2. Define global variables in HEADER2.HPP

HEADER2.HPP
#ifndef header2_hpp_
#define HEADER2_HPP_

int g_m = 1;//correct, global variable defined in HPP file//int
m;//correct, automatically initialized to 0
//extern int g_m = 1;//correct

//extern int g_m;//error, which is only declared undefined and needs to be int in a CPP file G_m =?; The definition is correct

#endif


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.