Search code examples
cstaticdeclarationimplementationforward-declaration

Declare a static function but implement it without the 'static' keyword in C?


Is it fine to write a forward declaration of a function with a static keyword but implemet it later in the file without the static keyword?

For example:

#include <stdio.h> /* printf */

static void func();

int main()
{
    func();

    return(0);
}

void func()
{
    printf("Hello World");
}

It compiles and runs without any errors, but would func be a static function or not and why?


Solution

  • C 2018 6.2.2 5 says a function declaration without a storage-class specifier (such as extern or static) is the same as using extern:

    If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern

    C 2018 6.2.2 4 says a declaration with extern after a declaration with static that is visible1 uses the internal linkage established by the static:

    For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration.

    So the behavior is defined to use internal linkage, and I am fairly confident there is nothing in the C standard that overrides this.

    Footnote

    1 An earlier declaration of a function declared at file scope could be hidden by a declaration of the same identifier in block scope. Then the earlier declaration would not be visible in that block.