0

I'm getting these errors with the following foo.h:

#ifndef __FOO_H__
#define __FOO_H__

unsigned char some_array[32];
unsigned char some_variable = 0;

void some_function(void);

#endif

foo.c:

void some_function(void)
{
    // Code using some_array and some_variable
}

However, if I were to instead do foo.h:

#ifndef __FOO_H__
#define __FOO_H__

void some_function(void);

#endif

foo.c

unsigned char some_array[32];
unsigned char some_variable = 0;

void some_function(void)
{
    // some code using some_array and some_variable
}

then it compiles with no errors. What's going on here?

Solution

The solution turned out to be to add extern to the header definitions of the variables, and to redefine them in the c file, although, I am unsure as to why this worked. foo.h

#ifndef __FOO_H__
#define __FOO_H__

extern unsigned char some_array[32];
extern unsigned char some_variable;

void some_function(void);

#endif

foo.c:

unsigned char some_array[32];
unsigned char some_variable = 0;
Kalcifer
  • 1,211
  • 12
  • 18
  • Please give the exact errors and the exact code. The code you have shown will not have the errors you claim. Suspect you are including the header into multiple C files and linking them all together. Which would result in multiple definitions of the variables. The first form of the header is almost always wrong. Headers should only have function declarations and extern or static variables. – kaylum Aug 16 '21 at 04:01
  • @kaylum I just solved it. It turns out the solution was to add extern to the variables in the header file, and then define them in the source file. – Kalcifer Aug 16 '21 at 04:07
  • Perhaps this will help: https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files/1433387#1433387 – rici Aug 16 '21 at 04:19

0 Answers0