The following tests are performed in vs2008 and vs2012
First build an empty test console application, the directory structure is as follows:
The Temp1 directory has two files: hello.h, hello.cpp
Temp1, hello.h
#pragma once
class Hello
{public
:
hello ();
};
Temp1, Hello.cpp
#include "hello.h"
#include <iostream>
Hello::hello ()
{
std::cout << "Temp1, hello" << std::endl;
}
The Temp2 directory also has two files: hello.h, hello.cpp
Temp2, hello.h
#pragma once
class Hello
{public
:
hello ();
};
Temp2, Hello.cpp
#include "hello.h"
#include <iostream>
Hello::hello ()
{
std:: cout << "Temp2, hello" << std::endl;
}
The engineering directory structure is as follows:
The main.cpp code is as follows:
#include <iostream>
#include "./temp1/hello.h"
int main (int argc, char *argv[])
{
Hello H;
System ("pause");
}
We know that there must be a problem, but where is the problem?
First, we compile the project, output display:
1>------started rebuilding all: Project: Test, configuration: Debug Win32------
1> Hello.cpp
1> Hello.cpp
1> main.cpp
1> is generating code ...
1>debug\hello.obj:warning LNK4042: object is specified multiple times; redundant designations have been ignored
1> test.vcxproj-> F:\project\TcpDemo\Debug\Test.exe
========== All regenerated: 1 successes, 0 failures, 0 ========== skipped
Note that this warning, because two files have the same name, even if they are in a different directory, but the generated obj files are in the same directory,
So there is only one obj file that causes the same name. This makes it clear that the Hello class has only one compilation success, and the other one is ignored.
This is not what we want, because even though these two classes have the same names, they are different.
The simple solution is to change the name (there is one more way to end it), but this will create a problem and repeat the definition.
Hello2.obj:error LNK2005: "Public: __thiscall Hello::hello (void)" (?? 0hello@ @QAE @xz) has been defined in Hello.obj
Add the namespace on it, such as: Hello in Temp1 in namespace Temp1 {...} In the Temp2, hello in the namespace temp2{...} In
This problem is solved, such as main.cpp code as follows, run the output is right.
#include <iostream>
#include "./temp2/hello.h"
#include "./temp1/hello.h"
int main (int argc, char * Argv[])
{
Temp1::hello H1;
Temp2::hello H2;
System ("pause");
}
In fact, I mainly want to say is the file name problem, change the filename OK,
But sometimes we do not want to change the name of the situation or not convenient to do.
Right-click on the duplicate CPP file-> properties-> output File-> object filename $ (IntDir) followed by the filename of the object we want to generate (as long as the obj file does not duplicate the name), such as:
Modify the Hello.cpp Object file name: $ (IntDir) Hello2 in the Temp2 directory.