ashmish2
ashmish2

Reputation: 2967

How can I handle global variables that are common between two projects?

I have two projects written in C: a client side and a server side, both of which contain lots of common global variables. I want to write a class (clientbot and serverbot using a interface Transaction) which will call the main function of each project.

I have moved all the common global variables in a header file and included it in both project. But on building it is throwing me linking error.

Error 3 error LNK2005: "int g_nBytestoSend" (?g_nBytestoSend@@3HA) already defined in transimpl.obj agentBot.obj

Can anyone suggest what I should do?

Upvotes: 0

Views: 645

Answers (2)

Mat
Mat

Reputation: 206859

You shouldn't put the actual variables in the header, only extern declarations of those. Put the actual variables in a separate .c or .cpp file and link with that.

In the header (lets call it globals.h), you put this declaration:

extern int g_nBytesToSend;

Then you create a new code file to hold the actual variables (say global.c):

int g_nBytesToSend;

Let's imagine you had three code files server.c, client.c and bot.c and that you're using gcc. You would build this like:

gcc -o server.o -c server.c
gcc -o client.o -c client.c
gcc -o bot.o -c bot.c
gcc -o globals.o -c globals.c
gcc -o mybot server.o client.o bot.o globals.o

(Try to keep your number of globals small.)

Upvotes: 2

escargot agile
escargot agile

Reputation: 22389

Did you protect the header file with ifndef?

Upvotes: 0

Related Questions