Karnivaurus Karnivaurus - 3 months ago 11
C++ Question

Multiple definition of variable

Here's my code:

main.cpp

#include "foo.h"

int main()
{
return 0;
}


foo.h

#ifndef FOO_H
#define FOO_H

class Foo
{
public:
Foo();
int bar;
}

#endif


foo.cpp

#include "foo.h"

Foo::Foo()
{
bar = 3;
}


Compiling this gives me the following error:

multiple definition of 'bar'


But I have include guards around the header file which defines
bar
, therefore how can it be defined more than once?

Answer

It's down to the missing semicolon at the end of the class declaration foo in foo.h.

That's confusing the compiler (it seems to be attempting to parse your constructor definition as the name of an object of type foo).

C++ ain't Java you know!