Hidden routines

Son Nguyen snguyen at nprdc.arpa
Thu Dec 22 05:07:19 AEST 1988



> I want to write a subroutine in C, called S.  I want S to be known outside.
> I also want to have two subroutines X and Y to be known ONLY to S (not known
> outside of S).  Either can be called by S, and each calls the other in a
> recursive way.  I also need to share several variables entirely within
> this context (shared between S, X, Y).  They can be static.  There will
> only be 1 instance of S (and therefore also of X and Y, but that should
> be hidden).  Main program M should be able to call S, but any references
> to X and Y will not be resolved by the module S.
> 
> How do I lay out the arrangement of source for S?  An example would be
> appreciated.  Thanks.

Well, in C++, it is easy by using 'class'.  However, in C, I am not pretty
sure.  Here is my plan:
	Assume that the user of your program is provided only 'S.o' which is
the object file of the C source code of S.
	
	First, create a header file named  'S.h'.  Within this file, you 
declare:

	/* Assume that S() will return an integer value */

		extern  int S();


	Second, create a C file called 'S.c'.  Within this file, you have
the codes of S(), _X(), and _Y() and along with the static variables shared only
by these routines.


	/* Assume that these variable are shared by S(),X(),Y() */

		static int A1;
		static int A2;
		     .
		     .


		int S()
		{
			int _X(), _Y();
			int a, b;
			     .
			     .
			     .
			/*  Call _X() from S() */
			a = _X();
			/*  Call _Y() from S() */
			b = _Y();
		}

		int _X()
		{
			int a;
			     .
			     .
			     .
			/*  Call _Y() from _X() */
			a = _Y();
		}

		int _Y()
		{
			int a;
			     .
			     .
			     .
			/*  Call _X() from _Y() */
			a = _X();
		}

	Finally, create a file 'M.c' which contains your main program.

	#include "S.h"

	main ()
	{
		int a, b, c;

		a = S();

		/*  If you attempt to call X or Y as below you get errors */

		b = X();
		c = Y();

	}

    My scheme is that in order to hide X and  Y from 'main' you should hide 
the declarations of X and Y from 'main'.  In addition, name your X and Y
routines such that they are totally different from the common users.
I believe that is how they do it in C++ when 'cfront' first attempts to
translate C++ source code into C.
     I hope to solve your problem.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Peter Nguyen		     +    MERRY CHRISTMAS TO EVERY ONE.
snguyen at aegean.nprdc.mil     +
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++



More information about the Comp.lang.c mailing list