tags:

views:

226

answers:

6

How can I declare and define a function so that it is only accessible from a single function? I can declare a function in another function. But since local function definitions are illegal (according to Visual C++) I must define the function at global scope, making it possible for other functions to call it.

void f1() {
    void f1_private();
    f1priv();
}

void f1_private() {
}

void f2() {
    f1_private(); // Legal
}

Is it possible to make f1_private only accessible from f1? If not, what are the uses for locally declared functions?

+3  A: 

No.

But you can write in C++, declare method inside class, make method private, and make another class friend of first class.

stepancheg
+8  A: 

You can put both functions into a single separate file and make the one you want to be less visible static. A static function in C is only accessible from the same source file in which it was declares (sort of a poor-man's namespace concept).

You then just expose the visible function in your header files as you'd normally do.

Joey
This is probably as close as you'll get, but it doesn't stop them from adding more functions to that file. Unless you were to compile it and force people to statically link it in as a library.
patros
Joey
+8  A: 

The best you can do is to put the two functions in their own file, and declare the "private" one to have static linkage (by prefixing the declaration with the word 'static'). Functions with static linkage are accessible only withing their compilation unit (usually meaning the same file, in most build systems).

If the non-private function has to be called from elsewhere, you would then have to either write its prototype in each file it is called from, or create a header file containing the prototype which is included in each file it is called from.

Tyler McHenry
A: 

// at the bottom of your .c file

static void foo()
{
}

void dude()
{
    // foo only accessible here, unless you have forward
    // declared it higher up in the file
    foo();
}

However, note that even static methods can be called outside file scope through a function pointer.

Magnus Skog
A: 

Put a comment on it.

//For use only by foo.

If someone is really gung-ho about using it, they will find a way despite your best efforts. Even if it means just copying and pasting the code, or refactoring the code. The best thing to do is let them know they shouldn't.

You can also encapsulate it by making it private, if it's in a class. Or static if it isn't.

patros
There is no such thing as a private function or class in C
Carson Myers
Well he's using the Visual C++ compiler.
patros
A: 

You can declare a separate class, with a public member for one function, and a private member function for the one you want only accessible from the other. If this is only used within a class you can make it an internal class.

Larry Watanabe