I am following Microsoft’s instructions to create OBJ files and then link them into an EXE.
https://learn.microsoft.com/en-us/cpp/build/reference/c-compile-without-linking?view=msvc-170
I compile The OBJ files like this:
CL /EHsc /c /std:c++20 SharedDependency.cpp Dependence1.cpp Dependence2.cpp Main.cpp
And I link them like this:
LINK SharedDependency.obj Dependence1.obj Dependence2.obj Main.obj /OUT:Main.exe
And the result is this: (Note: This error message is summarized)
Dependence1.obj : error LNK2005: it has already been defined --> SharedDependency::SomeFuction()
Dependence2.obj : error LNK2005: it has already been defined --> SharedDependency::SomeFuction()
Main.obj : error LNK2005: it has already been defined --> SharedDependency::SomeFuction()
fatal error LNK1169: One or more simultaneously defined symbols were found
ABOUT DEPENDENCIES
In SharedDependency.h
#pragma once
class SharedDependency
{
void SomeFuction();
};
In SharedDependency.cpp
#include "SharedDependency.h"
void SharedDependency::SomeFuction(){}
In Dependence1.h
#pragma once
class Dependence1
{
void SomeFuction(class SharedDependency SD);
};
In Dependence1.cpp
#include "SharedDependency.h"
#include "Dependence1.h"
void Dependence1::SomeFuction(SharedDependency SD){}
In Dependence2.h
#pragma once
class Dependence2
{
void SomeFuction(class SharedDependency SD);
};
In Dependence2.cpp
#include "SharedDependency.h"
#include "Dependence2.h"
void Dependence2::SomeFuction(SharedDependency SD){}
In the Main.cpp
#include "Dependence1.h"
#include "Dependence2.h"
class Main
{
Dependence1 D1;
Dependence1 D2;
};
int main(int argc, wchar_t **argv)
{
Main m;
return 0;
}
What is the correct way to compile this?