In src1.cpp, I define a class names "Test" and a function names "f1" that creates a instance of Test.
// src1.cpp
#include <iostream>
class Test {
int a = 1;
public:
Test() {
std::cout << "src1 Test\n";
}
};
void f1() {
Test t;
}
In src1.h, "f1" is exposed.
// src1.h
#pragma once
void f1();
In much the same way, src2.cpp and src2.h is created. A class with the same name and a function that constructs an instance of it.
// src2.cpp
#include <iostream>
class Test {
long a;
public:
Test() {
std::cout << "src2 Test\n";
}
};
void f2() {
Test t;
}
// src2.h
#pragma once
void f2();
Then in the main.cc, I call both f1 and f2.
// main.cpp
#include "src1.h"
#include "src2.h"
int main() {
f1();
f2();
return 0;
}
I compile by the following command with no warning and error.
g++ -Wall -o main main.cpp src1.cpp src2.cpp
And the program output is:
src1 Test src1 Test
It seems compiler allow the different definition of the class Test and both f1 and f2 call the constructor of Test in src1.cpp.
And when I compile with the reverse order like
g++ -Wall -o main main.cpp src1.cpp src2.cpp
And the program output changes to:
src2 Test src2 Test
When I replace the class Test
with a duplicate variable, the compile error occurs.
How does linker deal with the duplicate definitions in that case?