lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Matt Eisan once stated:
> I noticed most, if not all, examples of programs that involve writing
> modules for Lua define all C functions as static. Why is this and why isbot
> necessary?

  In C, a fuction declared as static:

	static int mymath_randomseed(lua_State *L);

will only be visible (i.e. usabled) by functions in the same file.  In other
words, it has what is called "file scope".  Once compiled, code outside the
file cannot see or call mymath_randomseed().  One result is that the static
function is hidden from code in other files.

  Another result is that the function is invisble to the linker (the code
that takes the output of the compiler and produces an executable) and in
some cases, this does have an impact.  One impact is the size of the
resulting program (for dynamically linked programs---for statically linked
programs the size doesn't matter).  Every non-static function increases the
size of the executable, since information about the function (name, address,
etc) needs to be stored and made available.

  Now, for the case of Lua modules, it's not necessary to define the C
functions as static---the module will most likely work.  But, if it defines
a non-static function used internally, say, foo(), and another module is
loaded that also defines a non-static function named foo(), the second
module will fail to load (or if it does, the program stands a good chance of
crashing).

  And if you think this shouldn't happen, it does.  I just checked a few Lua
modules, and the following modules:

		posix
		lzlib
		gdbm

  defined the following function:

		pushresults()

  Fortunately, all the definitions were defined as "static" so there are no
conflicts.

  -spc