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