'Simple cpp error? error LNK2005: "int AAA" (?AAA@@3HA) already defined in ConsoleApplication1.obj
ConsoleApplication1.cpp
#include <iostream>
#include "Test.h"
#include "Head1.h"
int main()
{
std::cout << "Hello World!\n";
}
Test.h
#pragma once
int AAA = 1;
Head1.h
#pragma once
#include "Test.h"
Head2.h
#pragma once
class Head2C
{
public:
void Print();
};
Head2.cpp
#include "Head2.h"
#include "Head1.h"
#include <iostream>
using namespace std;
void Head2C::Print()
{
cout << "Head2::Print() " << endl;
}
Why #pragma once can't work for this sample code?
The linker error : error LNK2005: "int AAA" (?AAA@@3HA) already defined in ConsoleApplication1.obj
Solution 1:[1]
Every non-constant variable should be defined only once in the entire program. #pragma once only ensures that it is defined once for each translation unit (cpp file). With two translation units, you are defining the variable twice in the entire program.
Make AAA constant or move the definition into a cpp file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VLL |
