Reputation: 464
I wondered if its possible that you can declare method A in a way that only a specific other method B can call A.
The reason beeing is that i want to restrict one method from beeing called from main (because of strange testing algorithms at college). If main called this method (which is an helper method), the whole programm would be trash.
So, how can i "forbid" main (or any other method) to call my dangerous method B ?
Upvotes: 1
Views: 206
Reputation: 2498
How about using backtrace and backtrace_symbol functions. backtrace man page
So inside this function A() check if it is called by specific allowed function and then only proceed or return (return with error or exit if needed).
Note: This method does not avoid getting your program instruction pointer (program counter) inside the dangerous function A (even when called from unwanted main()).
Upvotes: 1
Reputation: 2852
If you want to check this at run time, you can use backtrace
or similar function to determine who invoked your method. Be aware that the symbol names may be unavailable without the use of special linker options.
Upvotes: 0
Reputation: 6063
Put a and b into a separate compilation unit (object file of its own). Declare a static
to that compilation unit, make b globally visible, and also known in a specific header file.
Anything outside that compilation unit will not be able to call (or even "see") a, while b is fully visible for the rest of your program and very well able to call a.
If you want to make sure that nobody is able to change this, distribute only the compiled .o file and an appropriate header.
b.c:
static int a(int i){
...
}
int b(int x){
return a(x + 100);
}
main.c:
#include "b.h"
int main (int argc, char *argv[]){
int c, d;
c = b(100); /* works */
d = a(100); /* will not compile */
}
Upvotes: 6