A method of using global variables for C + + multiple files

Source: Internet
Author: User


Start the wrong approach

Declaring and defining variables in Global.h

int shareddata = 9;
Compilation error
Building Target:ctest
INVOKING:GCC C + + Linker
g++-  o "CTest"   
./src/ctest.o./SRC/GLOBAL.O /GLOBAL.O: (. data+0x0): ' Shareddata ' is defined several times
./SRC/CTEST.O: (. data+0x0): First time this definition
collect2: Error: LD return 1

The right approach,

In the Global.h header file declaration

extern int shareddata;


Class in the GLOBAL.CPP definition

int shareddata = 9;

And then call directly on the other file.

int main (void)
{
	cout<<shareddata<<endl;

return 0;
}

Without the header file, it is possible to declare it directly before the call.

extern int shareddata;

Look at the compilation

Make all 
building file:.. /src/ctest.cpp
INVOKING:GCC C + + Compiler g++-o0-g3-wall-c-fmessage-length=0-mmd-mp-mf "SRC/CTEST.D"
SR C/CTEST.D "-O" SRC/CTEST.O "". /src/ctest.cpp "
Finished building: ... /src/ctest.cpp
 
Building file:. /src/global.cpp
INVOKING:GCC C + + Compiler g++-o0-g3-wall-c-fmessage-length=0-mmd-mp-mf "SRC/GLOBAL.D"
SRC/GLOBAL.D "-O" SRC/GLOBAL.O "". /src/global.cpp "
Finished building: ... /src/global.cpp
 
Building Target:ctest
INVOKING:GCC C + + Linker
g++-  o "CTest"  . /SRC/GLOBAL.O   
finished building target:ctest


First step

CTest.cpp compiled to CTEST.O here the variables for the global file are actually used, since this phase only needs to include header files so that CTest.cpp know the declaration of the global file variable.


Part II

Global.cpp compiled to GLOBAL.O


Part III

Link CTEST.O and GLOBAL.O to generate executable ctest.






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.