How to access global variables and global functions in C + +

Source: Internet
Author: User

Global variables and global functions are relative to local variables and local functions, not {} or for, if and so on are global variables or global functions, the simplest is to declare in the same file.

For example, in Mian.cpp

#include <iostream>

int Gresult;

int Gadd (int a, int b) {

return a + B;

}

int main (int argc, const char * argv[]) {

Gresult = Aadd (2, 3);

}

In this case, the main function above is all global variables and global functions, in the entire file can be called to, that is, the global variable is the entire file in which it is located.

But the question is, what do we need to do with global variables in other files, or do we need only one global variable for the entire project.

The declaration of the time is the same, but in the call need to use the extern keyword in the file used to re-declare it.

For example:

We declare a global variable and global function in the base.cpp.

#include <iostream>

#include "base.h"

int Gresult;

int Gadd (int a, int b) {

return a + B;

}

void print () {

std::cout<<gredult<<std::endl;

}

Now we need to call global variables and global functions in mian.cpp;

int mian (int argc, const char * argv[]) {

Re-declare global variables and global functions in base.cpp;

extern int Gresult;

extern int Gadd (int a, int b);

extern void print ();

Gresult = Gadd (2, 3);

You can see that two printing results are all 5, because they operate on the same global variable;

std::cout<<gresult<<std::endl;

Print ();

}

How to access global variables and global functions in C + +

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.