Question

How to implement a "private/restricted" function in C?

I was asked a very interesting question during a C interview: How can you implement a function f() in such a way that it can only be called from a particular g() function. If a function other than g() tries to call f() it would result in a compiler error.

At first, I though this could be done with function pointers and I could get close to blocking the call at runtime. But I was not able to think of a compile time strategy. I don't even know if this is possible using ansi C.

Does anyone have any idea?

 45  70520  45
1 Jan 1970

Solution

 48

Here's one way:

int f_real_name(void)
{
    ...
}

#define f f_real_name
int g(void)
{
    // call f()
}
#undef f

// calling f() now won't work

Another way, if you can guarantee that f() and g() are the only functions in the file, is to declare f() as static.

EDIT: Another macro trick to cause compiler errors:

static int f(void) // static works for other files
{
    ...
}

int g(void)
{
    // call f()
}
#define f call function

// f() certainly produces compiler errors here
2009-09-09

Solution

 31

Put g() and f() in the same module, and declare f() as static. The static keyword makes f() available only to functions in the same module, or source file.

You might also want to mention that no other methods should be allowed in the module with f() and g(), otherwise they could call f().

PS - I really think Chris Lutz' answer is actually the best. It mentions this approach, but also a clever macro renaming that works with fewer environmental conditions (does not require the module file specifically for these two functions).

Note also that with a macro, you could do the following:

#define f() f_should_not_be_called_by_anything_except_g

Which would present a nice error message, and auto-completers (like Visual Studio) would show that tip when the user types f().

2009-09-09