Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring static global functions in header files

Tags:

c++

c

I came across a piece of code written by someone else. There are several global functions declared as static in header files. The functions themselves are defined in separate implementation files. AFAIK, static function definition isn't visible outside the translation unit where the function is defined. If so, what is the point of declaring static functions in header files?

// in some header file
static void foo();


// in some implementation file
static void foo()
{
....
....
}
like image 532
pic11 Avatar asked Mar 21 '12 10:03

pic11


1 Answers

Well, functions declared static are only visible in the source file they are defined in. Though declaring them in a separate header is not a good idea. I too, have seen some cases where developers have done this. They do it in order arrange them in an order so they can call one function from another. Here's what I mean:

/* In header */
static void plus(int);
static void minus(int);
static void multiply(int);

/* In source file */
static void minus(int v)
{
    /* So plus can be called in minus without having to define it
     * before minus */ 
    plus(); 
}

static void plus(int v) { /* code */ }

But IMHO this is a pretty disastrous way to do it. A better solution is to just prototype the static functions in the source file before implementing them.

like image 94
ApprenticeHacker Avatar answered Oct 01 '22 19:10

ApprenticeHacker