Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ multiple definitions of a variable

Tags:

I have 4 files (2 headers, and 2 code files). FileA.cpp, FileA.h, FileB.cpp, FileB.h

FileA.cpp:

#include "FileA.h"  int main() {     hello();     return 0; }  void hello() {     //code here } 

FileA.h:

#ifndef FILEA_H_ #define FILEA_H_ #include "FileB.h" void hello();  #endif /* FILEA_H_ */ 

FileB.cpp:

#include "FileB.h"  void world() {     //more code; } 

FileB.h:

#ifndef FILEB_H_ #define FILEB_H_  int wat; void world();   #endif /* FILEB_H_ */ 

when I try to compile(with eclipse), I get " multiple definition of `wat' " And I don't know why, it seems as it should work just fine.

like image 953
Bg1987 Avatar asked Jun 17 '12 14:06

Bg1987


1 Answers

I'm not going to include all of the details, but you define a global variable, wat twice in your compilation uint.

To fix, use the following:

FileB.h

extern int wat; 

FileB.cpp

int wat = 0; 

This (extern) tells the compile that the variable wat exists somewhere, and that it needs to find it on it's own (in this case, it's in FileB.cpp)

like image 105
Richard J. Ross III Avatar answered Oct 30 '22 17:10

Richard J. Ross III