Reputation: 7745
I don't want to put the static function definition in two source files(of the same module),
as that's duplicate.
Also I have to declare it as static, because I don't want other modules to use it.
What should I do?
Upvotes: 0
Views: 170
Reputation: 123568
This sounds like mutually exclusive requirements; you want a single implementation of a function to be shared between two translation units, but you want to declare it static
so that it isn't visible to other translation units. Unfortunately, C doesn't offer that kind of granularity; a symbol is either visible to all other translation units or it isn't.
You can fake it by putting the function definition in a header file (declared static), and then #include
it in the source files that need it:
#ifndef FUNC_H
#define FUNC_H
static void func() {...}
#endif
The thing is, each translation unit that includes this file will have a redundant implementation of the function. That may or may not be a big deal for you.
Personally, I'd just declare the function normally in its own translation unit, create a header for it, only include the header in the files that need to call that function, and document that function should only be called from those files.
Upvotes: 1
Reputation: 214780
The primary purpose of the static keyword is to create an object that will exist throughout the duration of the program. But all objects declared at file scope ("global") behave in this way, no matter if they are static or not: they have static storage duration.
But it also means that the object cannot be accessed outside the scope it is declared. Functions are declared at file scope ("global") and therefore a static function will only be accessible from the very same file it is declared in. So it doesn't make sense to declare such a function inside a header.
What I think you are trying to do is this:
// function.h
void the_func (void);
// function.c
#include "function.h"
static void the_private_func (void);
void the_func (void)
{
do_things();
do_private_things();
}
static void the_private_func (void)
{
...
};
// some_caller.c
#include "function.h"
...
the_func();
At least this it what makes sense in an object-oriented design.
Upvotes: 0
Reputation: 1
If the function is short or simple, you might define it (giving also its body) in a header file as a static inline function, e.g.
/* in header.h */
static inline int sum3(int a, int b, int c) { return a+b+c; }
But you really should read a good book on programming in C.
Upvotes: 0
Reputation: 143259
Not sure what do you mean by two files of the same module, but the point of static function is that their scope is limited to file, so the best you can do is to #include
one file into the other instead of linking them together. If I got your right...
Upvotes: 0
Reputation: 42013
Put the function header in a header file (.h).. can I suggest you find a good C tutorial ?
Upvotes: 3