Why does this code not work?

Problem: keep getting these two error messages and dont know why

Error 1 error LNK2005: "class product1 * productss" (?productss@@3PAVproduct1@@A) already defined in lib.obj practical.obj

Error 2 fatal error LNK1169: one or more multiply defined symbols found C:\Users\Username\Documents\Visual Studio 2008\Projects\Debug\University Work.exe 1

The code is long so i put it in pastebin http://pastebin.com/DjZrHFW1

This is what you get when you declare globals in headers. What you should do is
1
2
3
4
5
6
7
8
9
10
//foo.h
class Foo{...};

//foo.cpp
#include "foo.h"
Foo f[10];

//bar.cpp
#include "foo.h'
extern Foo f[10];
Or
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//foo.h
class Foo{
   ...
   static Foo f[10];
   ...
};

//foo.cpp
#include "foo.h"
Foo Foo::f[10];

//bar.cpp
#include "foo.h"
//and nothing else 

Notice that in the second case your object is called Foo::f and you can only call it f in methods of Foo.
Last edited on
yuck at the second method.
Why the second? I very much prefer it. The first one fills your cpps with externs. If you have several globals, it's ugly and a mess when you add or remove them. Doing a trick with defines, solves the latter bot not the former.
Because you are modifying the class in order to create objects. It really looks like a conceptual error of the difference between classes and objects.
it difficults code reuse too. It's very unlikely that you will need the same globals and their name remain meaningful.

The first one fills your cpps with externs. If you have several globals, it's ugly and a mess when you add or remove them.
You shouldn't have so many globals. Try to pass them as parameters instead.
Still, I don't see the management nightmare.
I'd say, the only globals you really need to have are the ones that belong in classes conceptually. But then, I'd have a hard time finding arguments for this. Anyway, I do see your point.
Topic archived. No new replies allowed.