开发者

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?


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.)


Did you protect the header file with ifndef?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜