Multiple source files share the same variables method

  extern variable can be placed before or function to indicate a variable or function is defined in another file, suggesting that the compiler encounters looking for other modules When this variable and function
definition.
  In addition, extern also be used to specify the link.

Usage Analysis:
     add extern in front of a variable such as: extern unsigned int Test;
compiler compile time, as will Test is outside! Test looks for this variable is defined elsewhere, if only so the compiler will add extern error!
For example, this:
     1> main.obj: error LNK2001: unresolved external symbol "int the Test" (the Test @@ 3HA?)
     1> E: \ WTL \ the Test \ the Test \ Debug \ test.exe: fatal error LNK1120: 1 an unresolved external command
because the extern keyword just that we quoted from an external variable, the value of the variable called Test, to remind the compiler to another file for this variable!

To not being given, the definition of a variable named Test it in other documents plus int Test. This will compile.

So suppose I have a main.c, source1.c, source2.c then I want to define a variable in the main inside, can be used in source1.c what to do with source2.c?
Very simple, define a value in the main.c: int data;
then two files are combined with point c: extern int data,
this variable can be common to these three .c file, the equivalent of a global variable .

Sample code:

//Main.c
#include
#include "source1.h"
#include "source2.h"
int data;
using namespace std;
void main()
{
    data = 4;
    adddata2();
    cout<<data<<endl;
    adddata1();
    cout<<data<<endl;
    cout<<"hello world "<<endl;
}

//Source1.c
#include "source2.h"
using namespace std;
extern int data;
void adddata2()
{
    data = data + 10;
}

//Source.h
#ifndef __SOURCE1_H__
#define __SOURCE1_H__
#include
void adddata1();
//Source2.c
#endif
 
#include "source1.h"
using namespace std;
extern int data;
void adddata1()
{
    data = data + 100;
}

//Source2.h
#ifndef __SOURCE2_H__
#define __SOURCE2_H__
#include
void adddata2();
#endif

 C multiple file shares the same variable (global variable)

when you declare a variable time is unsigned int data = 0;
when you want to use another source file in this variable.
Only need to add keywords: extern unsigned int data;
(note that this only shows that data is external variables, does not actually allocate storage space is not initialized.!)

Guess you like

Origin www.cnblogs.com/xiaosanxian/p/11141260.html