Hello there. I have not dabbled much in C++ in a long while but I am feeling like making a small project for fun. In this project I encountered this annoying problem on a secondary function of the application (i.e. not what it's core use is). Maybe I am just too tired and I am not seeing the horrible design or maybe I am missing something obvious :/
I have tried a few changes like moving declarations and definitions around, but it does not seem to go away.
Basically, bar.h uses a class defined in foo.h to instantiate from it and to create a macro using that instance. In turn, that macro will be used in both foo.cpp and main.cpp. I am getting the following error:
build/Debug/GNU-Linux-x86/bar.o:(.bss+0x0): multiple definition of `SOMEVAR'
build/Debug/GNU-Linux-x86/main.o:/home/alexandre/NetBeansProjects/tests/main.cpp:10: first defined here
collect2: ld returned 1 exit statuse
I have tried the simplest code possible (stripping *everything* that is not related to this issue) and get the exact same error so I know this is what is causing me trouble.
Here are the related files:
Code:
/*
* File: foo.h
* Author: alexandre
*
* Created on August 21, 2011, 12:49 AM
*/
#ifndef FOO_H
#define FOO_H
class Foo {
public:
void do_something(int t);
};
#endif /* FOO_H */
Code:
/*
* File: bar.h
* Author: alexandre
*
* Created on August 21, 2011, 12:49 AM
*/
#ifndef BAR_H
#define BAR_H
#define WHATEVER
#ifdef WHATEVER
#include "foo.h"
Foo SOMEVAR;
#define SOMEMACRO(a) SOMEVAR.do_something(a)
#else // WHATEVER
#define SOMEMACRO(a) //does nothing
#endif
#endif /* BAR_H */
Code:
/*
* File: foo.cpp
* Author: alexandre
*
* Created on August 21, 2011, 12:49 AM
*/
#include "foo.h"
void Foo::do_something() {
// whatever
}
Code:
/*
* File: bar.cpp
* Author: alexandre
*
* Created on August 21, 2011, 12:49 AM
*/
#include "bar.h"
Code:
/*
* File: main.cpp
* Author: alexandre
*
* Created on August 21, 2011, 12:48 AM
*/
#include "bar.h"
int main(int argc, char** argv) {
SOMEMACRO("whatever");
return 0;
}
This exact code generates the error. I am using the latest version of g++ on Netbeans IDE.
Finally, I have tried to add "guards" to try not to instantiate twice the same class. Apparently that does not do anything else different as I get the exact same problem.
Code:
#ifdef WHATEVER
#ifndef WHATEVER_INIT
#define WHATEVER_INIT
#include "foo.h"
Foo SOMEVAR;
#define SOMEMACRO(a) SOMEVAR.do_something(a)
#endif //WHATEVER_INIT
#else // WHATEVER
#define SOMEMACRO(a) //does nothing
#endif
Sorry for the code dumping but I think the structure here matters a lot to the problem.
Thank you very much.