C style 'static' functions

Johannes Pfau via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 19 12:05:41 PDT 2017


Am Wed, 19 Jul 2017 17:37:48 +0000
schrieb Kagamin <spam at here.lot>:

> On Wednesday, 19 July 2017 at 15:28:50 UTC, Steven Schveighoffer 
> wrote:
> > I'm not so sure of that. Private functions still generate 
> > symbols. I think in C, there is no symbol (at least in the 
> > object file) for static functions or variables.  
> 
> They generate hidden symbols. That's just how it implements 
> private functions in C: you can't do anything else without 
> mangling.

This is not entirely correct. The symbols are local symbols in elf
terminology, so local to an object file. Hidden symbols are local to an
executable or shared library.

> You probably can't compile two C units into one object 
> file if they have static functions with the same name - this 
> would require mangling to make two symbols different.

1) C does have mangling for static variables:
void foo() {static int x;}
==> .local	x.1796

2)
Object file? No, but you cant compile two translation units into one
object file anyway or declare two functions with the same name in one
translation file.
For executables and libraries, ELF takes care of this. One major usecase
of static functions is not polluting the global namespace.

-------------------------------------------------------
static int foo(int a, int b)
{
    return a + b + 42;
}

int bar(int a, int b)
{
    return foo(a, b);
}
-------------------------------------------------------
nm =>
0000000000000017 T bar
0000000000000000 t foo

-------------------------------------------------------
static int foo(int a, int b)
{
    return -42;
}

int bar(int a, int b);

int main()
{
    return bar(1, 2);
}
-------------------------------------------------------
nm =>
                 U bar
0000000000000000 t foo
                 U _GLOBAL_OFFSET_TABLE_
0000000000000011 T main

nm a.out | grep foo =>
000000000000063a t foo
0000000000000670 t foo

Additionally, when compiling with optimizations both foos are gone: All
calls are inlined, the functions are never referenced and therefore
removed. This can reduce executable size a lot if you have many local
helper functions, so D may benefit from this optimization as well.


-- Johannes



More information about the Digitalmars-d-learn mailing list