如何实现"民营/限制"在C函数? [英] How to implement a "private/restricted" function in C?
问题描述
我是一个C面试中问了一个很有趣的问题:你怎么能实现一个函数f()以这样一种方式,它只能从一个特定克()函数被调用。如果不是G其他()函数试图调用f()的话,就会造成编译错误。
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.
起初,我以为这可能是与函数指针做,我能得到接近堵在运行时调用。但我无法想象一个编译时的策略。我甚至不知道这是否使用ANSI C是可能的。
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.
没有人有任何想法?
推荐答案
下面是一种方法:
int f_real_name(void)
{
...
}
#define f f_real_name
int g(void)
{
// call f()
}
#undef f
// calling f() now won't work
另一种方式,如果你能保证 F()
和克()
是唯一的功能,在文件,正在申报 F()
为静态
。
Another way, if you can guarantee that f()
and g()
are the only functions in the file, is to declare f()
as static
.
编辑:另一个宏把戏引起编译器错误:
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
这篇关于如何实现"民营/限制"在C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!