Is there any case where the C static keyword should or could be used in header files for variables?

Viewed 1048

We can assume that the static keyword shall not be used in a header file - for variables.

A header file only contains extern declarations of variables — never static or unqualified variable definitions.

Is there any exception where the C static keyword should or could be used in header files for variables? Why?

2 Answers

I use static in header files only to define constants. Example:

MyProject.h

 static const int DebugLevel = 3;

Module.c

int foo(int x)
{
   if (DebugLevel>2) 
      printf("foo(int x) called with x=%d\n", x);
   ...
}

The advantages of this approach:

  • Changing one statement at a single location is automatically propagated in all modules.
  • Using const allows the compiler to optimize the if statement. The printf call might be removed too.
  • Using static allows the compiler to optimize the variable completely away, no memory is wasted.

Translation-unit-specific (i.e., C source file) information that needs to be a part of every compiled object file, but needs to be different for each input source file for some reason.

For example, debugging or build information used to track the origin of a specific object file. Or maybe an organization wants to embed copyright information directly into each object file.

For example, a "buildinfo.h" file:

#ifndef BUILDINFO_H_INCLUDED
#define BUILDINFO_H_INCLUDED

static char my_org_copyright[] = "Copyright ...";
static char my_org_build_info[] = "Compiled on " __DATE__ "@" __TIME__;

#endif

The usefulness of such data is debatable, but I have seen such constructs used in code produced by a very large corporation...

Related