C + + methods for using global variables multiple files

Source: Internet
Author: User


The practice of starting the error

Declaring and defining variables in Global.h

int shareddata = 9;
Compilation error
Building Target:CTestInvoking:GCC C + + linkerg++-  o "CTest"  ./src/ctest.o./src/global.o./SRC/GLOBAL.O   :(. data+0x0): ' Shareddata ' is defined more than once./SRC/CTEST.O: (. data+0x0): First time in this definition collect2: Error: LD returns 1

The right approach.

In the Global.h header file declaration

extern int shareddata;


Initialization in Global.cpp definition

int shareddata = 9;

And then call it directly in the other files to be able to

int main (void) {Cout<<shareddata<<endl;return 0;}

Do not include the header file, directly before the call can be declared.

extern int shareddata;

Look at the compilation

Make all Building file:.  /SRC/CTEST.CPPINVOKING:GCC C + + compilerg++-o0-g3-wall-c-fmessage-length=0-mmd-mp-mf "src/CTest.d"-MT "SRC/CTEST.D" -O "SRC/CTEST.O" ". /src/ctest.cpp "Finished building: /src/ctest.cpp Building file:.. /SRC/GLOBAL.CPPINVOKING:GCC C + + compilerg++-o0-g3-wall-c-fmessage-length=0-mmd-mp-mf "SRC/GLOBAL.D"-MT "Src/global . D "-O" SRC/GLOBAL.O "". /src/global.cpp "Finished building: /src/global.cpp Building Target:CTestInvoking:GCC C + + linkerg++  -o "CTest"  ./src/ctest.o.   /SRC/GLOBAL.O Finished building Target:ctest


The first step

CTest.cpp compiled to CTEST.O here it is useful to the variables of the global file, because this stage only needs to include the header file, let CTest.cpp know the global file variable declaration can be.


Part II

Global.cpp compiled to GLOBAL.O


Part III

Links to CTEST.O and GLOBAL.O, generating a ctest that can run the file.






Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

C + + methods for using global variables multiple files

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.