0

I am probably missing something obvious here but cannot find what.

I have a Utils.h file with a utility function that I want to use in multiple places. I know that the way to avoid redefinition compiler errors is to use include guards.

Here is what I have:

//----Utils.h----
#ifndef UH
#define UH
   void UtilFunc() { }
#endif

.

//----A.h----
class A {
   public:
      A();
      ~A();
};

.

//----A.cpp----
#include "A.h"
#include "Utils.h"

A::A() {
   UtilFunc();
}

A::~A(){ }

.

//----main.cpp----
#include "A.h"
#include "Utils.h"

int main() {
   A myA;
   UtilFunc();
   return 0;
}

My Visual Studio project has only files A.cpp and main.cpp included and when I try to compile I get:

  • Error LNK2005 "void __cdecl UtilFunc(void)" (?UtilFunc@@YAXXZ) already defined in A.obj HeaderIncludeTest C:\Users\michalis\source\repos\HeaderIncludeTest\HeaderIncludeTest\main.obj 1

  • Error LNK1169 one or more multiply defined symbols found HeaderIncludeTest C:\Users\michalis\source\repos\HeaderIncludeTest\HeaderIncludeTest\Debug\HeaderIncludeTest.exe 1

Mike mik
  • 91
  • 9

1 Answers1

0

Both A.cpp and main.cpp include Utils.h, therefore they both have a definition of UtilFunc, because you defined UtilFunc in Utils.h. It is a violation of one definition rule to have mutiple definitions of a non-inline function in one program. The linker detects it and complains about it.

You should either make UtilFunc inline, or put its definition in a separate compilation unit, Utils.cpp for example.

// Utils.h
#ifndef UH
#define UH
   void UtilFunc();
#endif
// Utils.cpp
void UtilFunc() {}
sparik
  • 1,181
  • 9
  • 16