This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

How to declare a Struct for Multiple files?

At the risk of receiving a good thrashing, I need to ask a basic C code beginner's question:

I want to declare/define an array of struct in a .h file that assigns it to xdata memory.

/* Struct.h */
xdata struct mode { int x,y,z; };
struct mode xdata type[5];

main.c () {
struct_init();
modify_struct();
}

struct_init () {
type[0].x = 1;
type[0].x = 2;
type[0].x = 3;
etc...
}

modify_struct() {
type[0].x = newvalue;
etc...
}

I'm confused as to how to make the struct visible to multiple files without getting:
"Multiple Public Definitions" or
"Unresolved External Symbol" etc...
Any guidance from the experienced would be appreciated. Thanks

  • 1. Declare and define the struct in exactly one C file.

    2. Create an extern declaration in the header file that is included in each C file.

    Jon

  • "I want to declare/define"

    STOP RIGHT THERE!

    The terms "declare" and "define" have distinct meanings in 'C'; they are not synonyms; they are not interchangeable.

    A correct understanding of the distinction is fundamental to answering your question.

    See this thread:
    http://www.keil.com/forum/docs/thread1847.asp
    (read it right through)

    And yes, you were right - this is a basic, standard, plain vanilla 'C' question - nothing specifically to do with 'struct', Keil or their C51 implementation.
    Consider yourself goodly thrashed! ;-)

  • Thank you Jon for the simple and brief description of the solution.

    I was declaring and defining as you described with one exception. In main.c I DEFINED the struct and the array of struct.
    In a global.h file I only DECLARED the array of struct. I assumed that since I had already DEFINED the struct mode, all the other files would recognize it.

    Thank you Andy for the additional information and the introductory thrashing!

  • In a global.h file I only DECLARED the array of struct

    Wrong. You did not just declare the array of structs --- you defined it, because there's no extern keyword in your supposed declaration. Technically, that makes this a "tentative definition", but effectively, this turns into a definition of the array in every module you #include "struct.h" in.

    You should almost certainly drop the "xdata" qualifier from the definition of the struct type itself.