Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!lll-winken!lll-lcc!ames!fxgrp!ljz From: ljz@fxgrp.UUCP Newsgroups: comp.lang.c Subject: Re: static stuff... Message-ID: <162@fxgrp.UUCP> Date: Wed, 18-Nov-87 01:43:52 EST Article-I.D.: fxgrp.162 Posted: Wed Nov 18 01:43:52 1987 Date-Received: Fri, 20-Nov-87 21:00:13 EST References: <3011@sigi.Colorado.EDU> Sender: ljz@fxgrp.UUCP Reply-To: fxgrp!ljz@ames.arpa (Lloyd Zusman) Followup-To: <3011@sigi.Colorado.EDU> swarbric@tramp.Colorado.EDU (SWARBRICK FRANCIS JOHN) Organization: Master Byte Software Lines: 67 In article <3011@sigi.Colorado.EDU> swarbric@tramp.Colorado.EDU (SWARBRICK FRANCIS JOHN) writes: >First, what is the significance of making a static function? > >Second, aren't all global variables automatically static. Is there any >reason to explicitly call them static? Yes, all global variables are static, as are all functions, for that matter. The "static" keyword in front of a global variable or a function is used to indicate that the variable or function is only known within the file it is defined in. For example, consider the following two files, foo.c and bar.c: /* beginning of file foo.c */ int foo_1 = 0; static int foo_2 = 0; foo_func_1() { return foo_1; } static foo_func_2() { return foo_2; } /* end of file foo.c */ /* beginning of file bar.c */ extern int foo_1; extern int foo_2; extern int foo_func_1(); extern int foo_func_2(); main() { printf("foo_1 = %d\n", foo_1); printf("foo_2 = %d\n", foo_2); printf("foo_func_1() returns %d\n", foo_func_1()); printf("foo_func_2() returns %d\n", foo_func_2()); } /* end of file bar.c */ Compiliong the files foo.c and bar.c separately will result in no errors (unless I made a typo somewhere). However, if you try to link them, you will find that the variable "foo_2" and the function "foo_func_2" are unknown references in the routine "main". This is because they are only known within the file foo.c due to the "static" keyword. Although using the "static" keyword in this way might be a bit confusing, the feature is a nice one, as it minimizes the number of external symbols that occur. If I create a library and use a word like, say, "counter" as a global within one of the files I'm compiling from, but that variable is only known within that file, I can declare it to be a static global. That way, if you link to my library and happen to use your own global (static or otherwise) named "counter", there won't be a name conflict. Same goes for functions. --- Lloyd Zusman, Master Byte Software, Los Gatos, California "We take things well in hand." ...!ames!fxgrp!ljz