-1

I have a project with multiple file as below:

//header.h
class example {...}

//variable.h
#include "header.h"
example ex;

//main.cpp
#include "variable.h"
....

//src1.cpp
#include "variable.h"

when compiling the compiler error as: multiple definition of "ex" I dont understand why, I want to use "ex" in main.cpp and src1.cpp, how should I do. Thanks,

  • duplicate ? https://stackoverflow.com/questions/11072244/c-multiple-definitions-of-a-variable – user30701 Jun 27 '18 at 10:11
  • 2
    Possible duplicate of [c++ multiple definitions of a variable](https://stackoverflow.com/questions/11072244/c-multiple-definitions-of-a-variable) – Søren D. Ptæus Jun 27 '18 at 10:35
  • Just a clarification: you'd have exactly the same problem without "header.h" if "variable.h" had `int ex;` in it. – Pete Becker Jun 27 '18 at 12:02

2 Answers2

1

By #including variable.h in both main.cpp and src1.cpp, you have defined variable ex twice. The linker (not the compiler) won't like this.

Instead, change variable.h to look like this:

extern example ex;

And put:

example ex;

in (say) src1.cpp.

And yes, use include guards also, but that's not the problem here.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
0

Use include guards in header.h and variable.h:

#ifndef HEADER_H
#define HEADER_H

class header {...}

#endif
rcs
  • 73
  • 6