I have two files as below:
Test1.h
#ifndef TEST_H
#define TEST_H
int i = 10;
#endif
Test2.cpp
#include <iostream>
#include "Test1.h"
int main()
{
std::cout << i << std::endl;
}
I know I can solve this by using extern or const in Test1.h.
But my question is that "I don't understand the error".
error LNK2005: "int i" (?i@@3HA) already defined in Test1.obj
error LNK1169: one or more multiply defined symbols found
How can int i have multiple definitions?
- The header file has include guards.
- When I include the header file it should mean that everything gets copied in
Test2.cppand it should become:
Test2.cpp
#include <iostream>
int i = 10
int main()
{
std::cout << i << std::endl;
}
And header file should become irrelevant at this point after everything being included.
My other question is if I declare int i with extern in header file and include it in .cpp, then would it be an example of external linkage? Because generally I have seen external linkage between two .c or .cpp as in here but if you explicitly include the file is it still regarded as i having external linkage?
#includedirective; just don't forget that it's done both source files. Test1.cpp also has#include "Test1.h", so it has the same definition ofias Test2.cpp has. That's why the linker is complaining. - Pete BeckerTest1.objinvolved, which you failed to mention in your question. Please show the commandline you used to compile, as well as all source files involved - M.Mg++ Test1.h Test2.cpp -o main. You don't need to specify the header in the compile command. - hgieselTest1.htoTest2.hand the error is completely gone. It happened because I renamedTest1.cpptoTest1.h. - user103214