tags:

views:

86

answers:

2

I have two files:

hudwidgets.c

#include "osd.h"
#include "osdadd.h"
#include <stdio.h>

struct TextSize tsize;
char buff[50];

void hud_draw_lin_compass(int cx, int cy, int tick_maj, int tick_min, int range, int heading)
{
    .. important code that uses buff ..
}

hud.c

#include "hudwidgets.h"
#include "hud.h"
#include "osd.h"
#include "osdadd.h"

.. some code ..

void hud_rc_plane_single_frame()
{
    fill_mem(0x0000);
    if((frame / 50) % 2 == 0)
    {
        get_next_warning(buff);
    }
    .. some more code ..
}

The problem I have is that when I try to compile this, the compiler complains of no buff defined, but when I try to define it, the linker complains of two buff variables. Catch-22. To this end, I am asking two questions:

  1. how to fix this, and;

  2. if it is possible to use the same variable thus saving memory because only one variable needs to be allocated (working with a memory constrained microcontroller.)

+8  A: 

You need this in the top of hud.c, and any other .c file you use them from:

extern struct TextSize tsize;
extern char buff[50];

The extern keyword tells the compiler that the "actual" variables already exist, in some other unit (file), and the linker will fix it all up for you in the end.

If you're doing this on a large scale in a project, consider how you might encapsulate globals in one place, and create a shared .h file that declares these things as "extern" for all the places that you use them from.

quixoto
What do you mean by other c file? There are plenty of others. So, should I put it in "main.c", or "hud.c", or "hudwidgets.c" or something else?
Thomas O
Anywhere you use these variables. In your example above, it's "hud.c". But any file where you access these globals except the actual file you define them in, you need to declare them "extern".
quixoto
@Thomas If all those `.c` files include a common header, you can put it in there. It's fine if `hudwidgets.c` includes that file too, you can extern a variable and then declare it later in the same file
Michael Mrozek
@Thomas O: Any file that uses it. Typically you'll put the extern declaration in some header that all of those files include.
Chuck
Thanks guys. Correct answer; it works. I'll mark this as the accepted answer when it lets me (6 minutes.)
Thomas O
+2  A: 

use "extern char buff[50];" in the files where you have not initialized the buff and want to use it. This tells that the declaration is done in other files and you are using it in this file.

chaitanyavarma