5

While developing a library using C, what are your recommendations about variable and function scoping?

In C++, OOP and namespaces made the whole thing a lot easier. But how to do that with plain C? Specially how to use the keywords static and extern in headers and code files to manage scoping?

gnat
  • 20,543
  • 29
  • 115
  • 306
Gulshan
  • 9,532

1 Answers1

13

On extern: As a rule, don't. The only thing that should be shared between files are definitions, via headers: function declarations (in C files) link externally without scope keywords. (Global variables are bad enough by themselves: linking them into other files just exacerbates the problem.)

You should use static in the (C file) definition of any file-local functions that you aren't exposing (via headers) to other files (it omits the function from external linking, keeping the global namespace unpolluted). (You could make any global variables in a file static for the same reasons, but you're better off just not having global variables.)

As for namespacing, your library should agree on a common prefix for all function / macro / struct / constant names (Lua uses lua_ for core API stuff (LUA_ for constants), luaL_ for auxiliary stuff, and various other 'lua-plus-a-letter-and-underscore' prefixes for internal stuff).

As for actual inner-function-scopes like this:

void example()
{
  char* msg = "Hello world!";
  msg[1]='a';
  msg[3]='d';
  {
    FILE * fOutput;
    fOutput = fopen ("out.txt","w");
    if (fOutput)
    {
      fputs (msg,fOutput);
      fclose (fOutput);
    }
  }
}

I personally love them and feel they're a great solution to ANSI C's "must declare all variables before any other statements" restriction, but most people tend to just keep their variable scopes flat at the root of the function.