problem with extern variable


i have got 2 cpp files & a header file, which i have included in all 2 cpp files. its like this

abc.h
extern uint32_t key;

a.cpp

#include "abc.h"
uint32_t key;
int main
{
.............
}

b.cpp
#include "abc.h"

int main
{
printf("Key: %.8x\n", key);
.............
}

now when i compile a.cpp, there is no error. but when i compile b.cpp it gives error
"undefined reference to `key'". please help me in finding the problem in this code. thnx
First, I trust you are compiling both files. Second, you have main in both C++ files. This should generate a linker error. Third, try putting an extern just before key in b.cpp for safety.

-Albatross
i am compiling both files separately.
putting extern before key is giving error.
http://www.cplusplus.com/forum/beginner/1/

This would be resolved much faster if you were more specific, posted the commands to compile, and posted the entire error messages.
Last edited on
i am compiling using g++ -o a a.cpp & g++ -o b b.cpp.
error while compiling b.cpp is "undefined reference to `key'"
Ok. So you are trying to compile to separate executables... Well, the first extern declaration (in abc.h) tells the compiler that the symbol will become available at linking--in other words, you are telling it to let you refer to something that you'll provide elsewhere.

In the first case, with a.cpp, key is defined.

In the second case, with b.cpp, key is not (hence the undefined reference linker error).

All symbols must be defined once and only once. This is called the One Definition Rule (ODR).

If you remove one of the main functions, you should find that you can compile both files into a single executable, using g++ -o ab a.cpp b.cpp, and in both source files you can use key. That is the point of using extern, to make a symbol accessible across different object files.

In the case of two separate executables, there is no need for the header abc.h. Each file should define key.

It all comes down to your intentions, as to how to solve the problem.
Last edited on
Topic archived. No new replies allowed.