[comp.lang.c] best way to share structs between modules?

tannerr@prism.cs.orst.edu (Ryan Tanner) (06/23/91)

I've looked through my C manuals, and there seems to be little information
to help the beginner with header files.  What is the best way to share
structs between modules?  I finally got it to work with typedefs, but
it seems to  me that it might be done another way.  Help.

Ryan (tannerr@prism.cs.orst.edu)

bhoughto@pima.intel.com (Blair P. Houghton) (06/24/91)

In article <1991Jun22.214830.22490@lynx.CS.ORST.EDU> tannerr@prism.cs.orst.edu (Ryan Tanner) writes:
>I've looked through my C manuals, and there seems to be little information
>to help the beginner with header files.  What is the best way to share
>structs between modules?  I finally got it to work with typedefs, but
>it seems to  me that it might be done another way.  Help.

[Donning carmine robes and mortice; for we travel
now into the realm of authoritarian religion. >:-) ]

When the structure is defined (struct foo bazz = { 1, "hello", ... };)
in the source file (bar.c), write the struct
declaration (struct foo { int i; char *s; ... };)
along with an external declaration (extern struct foo bazz;)
in the headerfile (bar.h) and include the headerfile (bar.h)
in any source file that uses the struct, as well as in the
first source file, so that object's definition's structure-
tag (foo) is in scope.

Once again:

	bar.h:
		#ifndef _BAR_H
		#define _BAR_H

		struct foo {
		    int i;
		    char *s;
		};
		extern struct foo bazz, *bletch;

		#endif

	bar.c:
		#include "bar.h"
		struct foo bazz = { 1, "hello" }; /* initialization optional */
		struct foo *bletch;
		/* code may now reference bazz and bletch */

	other.c:
		#include "bar.h"
		/* code may now reference the same bazz and bletch */

(Note that the structure declaration in bar.h is essentially
a typedef where the type name is "struct foo").

There's no really good guideline for deciding which source
file should be the one that contains the completed
definition (bazz).  Generally, it's logical to define it in
the place where it is used the first time in a normal run
of the program, though often it is part of a personal
library of utility functions, and not actually created by
any of the utilities.  (String functions don't define any
strings, for example, though your personal string library
may define a structure that holds strings and their attributes,
as well as the functions that massage these data; the structure
declarations would be in the .h file, and the functions in
the .c or .o file).

				--Blair
				  "Nomini patri et fili et
				   spiritu sanctii:  Amen."