Topic : global var in 2 c-files

Forum : ST7/STM8

Original Post
Post Information Post
April 18, 2012 - 1:18pm
Guest

Hi,

I want to use a global variable in 2 c-files. I wrote a headerfile globalvar.h with
#ifndef GLOBALVAR
#define GLOBALVAR
unsigned char mytestbyte;
#endif

and included it in program1.c and program2.c
Program1.c and program2.c belong to the same project.
After Build Project I get: ***ERROR 104 : MULTIPLE PUBLIC DEFINITIONS symbol mytestbyte
Is there a convenient way to solve this problem?
I did the same using another mcu and a gnu compiler. There was no problem.
I have to manage a lot of global variables and want to save a lot of writing stuff.

Regards
cs

Replies
Post Information Post
+1
0
-1
April 19, 2012 - 9:28am
Raisonance Support Team

Hi,

That's an easy one: You should never have a definition (a declaration that "creates" an object) in a header file.

The trick is to have all object *declarations* in a header file, and the object *definitions* in a C file (usually with the same name as the header).
So in your case, in file globalvar.h:

#ifndef GLOBALVAR
#define GLOBALVAR
extern unsigned char mytestbyte;
#endif

And in file globalvar.c:

unsigned char mytestbyte;

That's it!

+1
0
-1
April 19, 2012 - 11:23am
Guest

Hi,

Thanks for your answer. In this case I have to write each variable in two files.
In WinAVR I included only the globalvar.h in every c-file. Maybe the linker of this
GNU compiler works not C standard like. No matter. I'll do it like suggested.

Best regards
cs