Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem with extern variable

I have got 2 cpp files & a header file, which I have included in both cpp files. It's 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.

like image 950
user349146 Avatar asked Oct 22 '25 15:10

user349146


1 Answers

To share a variable, you normally have something like this:

// A.h
extern int key;
void show();

//a.cpp
#include "a.h"

int main() { 
    key = 1;
    show();
};

// b.cpp
#include "a.h"
#include <iostream>

int key;

void show() { std::cout << "Key = " << key; }

There are a couple of points to not here. First of all, you put the extern declaration in a header, and include it in all the files that use the variable. Define the variable (without the extern) in one and only one file. Only one file should contain a function named main.

Edit: to build this, you compile each file by itself, but you have to link the two files together. For example, using gcc you could do something like:

gcc -c a.c
gcc -c b.c
gcc a.o b.o

The first compiles (but does not link) a.c. The second does the same with b.c The third actually links the two together and produces a binary image you can execute (traditionally named a.out, though, for example, on Windows this is normally changed to a.exe).

like image 174
Jerry Coffin Avatar answered Oct 25 '25 05:10

Jerry Coffin