Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 421
  • Last Modified:

LNK2005 error redefinition

I'm getting a LNK2005 error due to redefinition of some functions.  The project has a main (test.cpp), two classes (myclass1.h, myclass1.cpp, myclass2.h, myclass2.cpp), and another header file (morefuncs.h) that is not a class but contains some functions.

I've used #pragma once in all header files.

The test.cpp #includes both header files for the classes.

If I include the header file for the additional functions, #include morefuncs.h into only one of the class header files, everything is fine.  However if I try to include morefuncs.h into the second class, I get the above linker redefinition error.  I'm assuming this is becasue the morefuncs is not a class but simply a header file that contains functions.

I'd rather not make morefuncs a class. Is there a way to include it into multiple other classes without a redefinition problem?
1 Solution
#pragma once prevents h-file to be included twice to the same source file. But it doesn't prevent h-file to be included number of times to different source files in the project. If h-file contains function implementations, this causes linker error.
You have one the following options:
1) Move function implementations to additional cpp file and leave only prototypes in h-file
2) Declare all functions in h-file as inline
3) Declare all functions in h-file as static
4) Divide h-file on two parts: declaration and implementation:

// declaration part
// function prototypes

// function bodies

Include this h-file to number of source files, and define only once IMPLEMENTATION:

#define IMPLEMENTATION    // only in one source file
#include "MyFile.h"

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now