0

I have a file p2.cpp and 2d.cpp which I'm trying to link with 2d.h. I have included 2d.h in both .cpp files and I'm getting an error:

2d.obj : error LNK2005: "float (* v)[3]" (?v@@3PAY02MA) already defined in p2.obj
1: fatal error LNK1169: one or more multiply defined symbols found.

What should I do?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sushma
  • 1
  • use header guard: http://stackoverflow.com/q/4767068/992406 – houssam May 04 '15 at 10:48
  • 1
    What does the `*v` block look like in the header file? It should be a declaration only, and you want a definition in exactly one cpp file. – Rup May 04 '15 at 11:08

1 Answers1

0

I have a file p2.cpp and 2d.cpp which I'm trying to link with 2d.h. I have included 2d.h in both .cpp files and I'm getting an error:

Each symbol may only be defined in a program once (refer One definition rule). I'm not sure what you're header file looks like, but typically this means something to the effect of defining something in you're header file that is included in more than one compilation unit. You could "extern" it in you're header, and ensure that it is defined in a separate compilation unite.

From the compiler error it looks like you've define an array of pointers to functions in your header file. Extern this and provide a single definition in a source file.

This code effectively causes the problem:

//--- Def.h
#ifndef DEF_H
#define DEF_H

float foo();

/*extern */float (*floatFunctionArray[3])();

#endif  /* DEF_H */

//--- Def.cpp
#include "Def.h"

float foo()
{
   return 0;
}

float (*floatFunctionArray[3])() =
{
   foo, foo, foo
};

//--- main.cpp
#include "Def.h"

int
main(int argc, char** argv)
{
   return 0;
}

Adding the commented out "extern" solves the issue.

Werner Erasmus
  • 3,988
  • 17
  • 31