Reputation: 59
I have a function declared in .h file.
void func1();
In .c file apart from func1 I define func2 and use it in definition of func1 (func2 is NOT declared in .h file)
void func2()
{
do something;
}
void func1()
{
func2();
do something else;
}
Why I do this is because I don't want to put declaration of func2 in .h file (this function wouldn't be used outside the module). So yeah, I want to create kind of "private" function in C. My questions are: Is this a bad practice? Is there another way to create "private" functions in modules in C?
Upvotes: 1
Views: 317
Reputation: 12412
No, it's not bad main()
being a prime example.
however if the function is not defined in an header file it's only properly callable from the .c file itself, and so should be declared static
static void func2()
{
do something;
}
making it static will make it unavailable to external callers (so, you can't make main() static)
To police this pattern there's a gcc
option to warn about non-static functions not previously prototyped
-Wmissing-prototypes
Upvotes: 4
Reputation: 71
This is a perfectly fine practice that is used a lot. This is indeed used to cretae a kind of "private" function. When doing this you normally also declare the function as static, eg.:
static void func2()
{
do something;
}
That way the function is only available for use by code from this c file. Otherwise you can still use the function in another file if you know the prototype.
Upvotes: 2