Unsolved Compile two cpp files with QT
-
Hello! Need your advise
Need to compile:#ifndef TEST_H
#define TEST_Hint a = 0;
void simplePrint ();#endif // TEST_H
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <Test.h>using namespace std;
using std::ios;void simplePrint ()
{
cout << "a " << a << endl;
}#include <iostream>
#include <Test.h>
using namespace std;
using std::ios;int main()
{
cout << "Hello World!" << endl;
return 0;
}PRO_FILE
TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qtSOURCES +=
Test.cpp
main.cppHEADERS +=
Test.h:-1: error: debug/main.o:C:\Users\iceberg\Desktop\Test4\build-Test4-Desktop_Qt_6_2_3_MinGW_64_bit-Debug/../../TestBsae/Test4/Test.h:6: multiple definition of `a'; debug/Test.o:C:\Users\iceberg\Desktop\Test4\build-Test4-Desktop_Qt_6_2_3_MinGW_64_bit-Debug/../../TestBsae/Test4/Test.h:6: first defined here
-
This is a basic C/C++ question an nothing to do with the Qt library.
Your Test.h declares a and allocates storage for it.
When you compile Test.cpp it includes Test.h. The resulting Test.o object file contains space for a.
When you compile Main.cpp it includes Test.h. The resulting main.o object file contains space for a.
When the linker combines Test.o and main.o to make the resulting executable it fails because there are two a variable space allocations in the same scope.There should only be space allocated in one place for a.
Test.h#ifndef TEST_H #define TEST_H extern int a; // ^^^ A declaration of the existence of "a" so that main.cpp can be compiled // No space allocated void simplePrint (); #endif // TEST_H
Test.cpp
#include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> #include <Test.h> using namespace std; using std::ios; int a = 0; // ^^^ The storage for "a" should be in one CPP file only void simplePrint () { cout << "a " << a << endl; }