Reputation: 647
I was trying to implement access specifier (not sure if that is called access specifier)
The purpose is to make a function (func2) callable only at one place(inside func1).
int func1 ()
{
// Make func2 callable only here`
#define FUNC2_CALLABLE
func2();
#undef FUNC2_CALLABLE
}
#ifdef FUNC2_CALLABLE
int func2 ()
{
return 1;
}
#endif // FUNC2_CALLABLE
func2 should be callable only from func1 and not from any other place in the code.
Does the above code serve the purpose ? Any alternative suggestions
< Edit 1 >
How about doing it this way
int func2()
{
#ifdef FUNC2_CALLABLE
return 1;
#endif
}
Will this work ? < / Edit 1>
Upvotes: 3
Views: 1516
Reputation: 1412
Maybe you can use static
keyword .
But the function with static
is accessible for all the code in the same file. Other files cannot access it.
Upvotes: 0
Reputation: 57784
There is no real way to do it. The best that can be done in standard C is to make func2 static and define it close to the bottom of the source file:
static int func2 ()
{
return 1;
}
int func1 ()
{
func2();
}
(end of file)
Upvotes: 0
Reputation: 33457
That will give you a linker error of func2 not found (func2 won't be defined if you use that).
I think you might be looking for static.
static int fake(int x) { return x * 2; }
int doSomething(int x) { int tmp = fake(x); doOtherThings(); }
The fake would not exist outside of the compilation unit (file basically).
As for allowing a function to only be called from another function, that doesn't make much sense. Just inline the code if that's your end goal.
Upvotes: 1