Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining an extern variable in the same header file

Tags:

c++

c

extern

I am wondering if it is possible to both declare and define an extern variable in the same header file. I need the variable to be referenced across multiple files, and while I realize there are better ways to achieve this, using extern is the only option in this case. So is it possible to do:

// in main.h
extern int foo;
int foo;

etc...

And then any file which includes main.h will have access to foo? Many examples reference defining the extern'd variable in a separate cpp file, but I'm just wondering if the way I suggested will cause problems across the rest of the project.

like image 424
Jesavino Avatar asked Dec 02 '22 16:12

Jesavino


2 Answers

If you put a definition in a header file, you will end up with multiple definitions when multiple source files are involved.

For example, suppose both main.c and other.c include foo.h. When you compile each of these files you'll get main.o and other.o, both of which have a definition of int foo. If you then attempt to link main.o and other.o into a single executable, you'll get a linker error stating that int foo was defined twice.

To do this properly, you declare your variable in the header file as extern int foo. Then, in one (and only one) source file you define the variable with int foo.

like image 147
dbush Avatar answered Dec 05 '22 06:12

dbush


Real definitions (not extern) should not be in a header file.

If you want to have one global variable available from different cpp, you should make two things: definition in one cpp and extern declaration in h.

E.g.:

// global.h
extern int foo;

and

// global.cpp
int foo;

Then in any file where foo is needed:

#include "global.h"

And, of course, global.cpp have to be part of project (compiled with other files)

like image 22
VolAnd Avatar answered Dec 05 '22 06:12

VolAnd