在C中查找函数调用者

Mat*_*att 1 c function

嘿所有,我只是想知道是否有可能获得在函数内运行的程序的名称?

这是一个例子:

我打电话给:./ runProgram

main() {

A();

}

function A() {

// Possible to retrieve "runProgram" if I cannot use main's argc(argv) constants??
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ini 5

编译器依赖,所以:

$ cc --version
i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646)
Run Code Online (Sandbox Code Playgroud)

制作节目

$ more x.c
int main(int argc, char *argv[]) {
      printf("program: %s\n", argv[0]);
    foo();
}


int foo() {    
}

$ make x
cc     x.c   -o x
x.c: In function ‘main’:
x.c:2: warning: incompatible implicit declaration of built-in function ‘printf’
$ ./x 
program: ./x
Run Code Online (Sandbox Code Playgroud)

获取argc/v变量的全局名称

$ nm ./x
0000000100000efe s  stub helpers
0000000100001048 D _NXArgc
0000000100001050 D _NXArgv
0000000100001060 D ___progname
0000000100000000 A __mh_execute_header
0000000100001058 D _environ
                 U _exit
0000000100000eeb T _foo
0000000100000eb8 T _main
                 U _printf
0000000100001020 s _pvars
                 U dyld_stub_binder
0000000100000e7c T start
Run Code Online (Sandbox Code Playgroud)

添加全局名称,声明为extern,并考虑到重整.

$ more x2.c
int main(int argc, char *argv[]) {
      printf("program: %s\n", argv[0]);
    foo();
}


int foo() {
    extern char **NXArgv;
    printf("in foo: %s\n", NXArgv[0]);

}
Run Code Online (Sandbox Code Playgroud)

运行恐怖

$ make x2
cc     x2.c   -o x2
x2.c: In function ‘main’:
x2.c:2: warning: incompatible implicit declaration of built-in function ‘printf’
x2.c: In function ‘foo’:
x2.c:9: warning: incompatible implicit declaration of built-in function ‘printf’
$ ./x2 
program: ./x2
in foo: ./x2
Run Code Online (Sandbox Code Playgroud)

请不要告诉我的妈妈.

  • 尽管存在所有这些其他的弊端,你至少可以`#include <stdio.h>`并让编译器闭嘴.它不会伤害. (4认同)