I’m trying to share the same variable between two .cpp files, they include the same .h file.
But I’m getting linking errors, telling me that I have multiple definitions. Which I find awkward, since I’m using include guards
//main.cpp
#include <cstdio>
#include "shared.h"
int main(){
shared_int = 5;
printVal();
return 0;
}
//shared.h
#ifndef INCLUDE_GUARD_H
#define INCLUDE_GUARD_H
#include <cstdio>
#include <cstdlib>
int shared_int;
int printVal();
#endif
//shared.cpp
#include <cstdio>
#include "shared.h"
int printVal(){
fprintf(stderr,"a: %d\n",shared_int);
return 0;
}
I’m comping like
g++ shared.cpp -c;g++ main.cpp shared.o
shared.o:(.bss+0x0): multiple definition of `shared_int'
/tmp/cci8w8Am.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
thanks
Update:
The ‘extern’ still doesnt work, but now I get a undefined reference
These are the updated files
//shared.h
#ifndef INCLUDE_GUARD_H
#define INCLUDE_GUARD_H
#include <cstdio>
#include <cstdlib>
//extern "C" int shared_int;//i've tried both
extern int shared_int;
int printVal();
#endif
//shared.cpp
#include <cstdio>
#include "shared.h"
int printVal(){
fprintf(stderr,"a: %d\n",shared_int);
return 0;
}
//main.cpp
#include <cstdio>
#include "shared.h"
int main(){
int shared_int = 5;
printVal();
return 0;
}
This is how I compile
g++ main.cpp shared.o
shared.o: In function `printVal()':
shared.cpp:(.text+0x6): undefined reference to `shared_int'
collect2: ld returned 1 exit status
The declaration in your header file needs an
extern:Then, you will need an actual instance of the definition in one C++ file (such as in
shared.cpp):The include guards you’re using here are good practice, but they won’t have any effect in this situation. The include guard prevents the header file from being included more than once in the same source file. Such a situation normally doesn’t happen unless you have header files indirectly included from other header files.