Get a pointer to the current function in C (gcc)?

2019-01-18 04:52发布

is there a magic variable in gcc holding a pointer to the current function ?

I would like to have a kind of table containing for each function pointer a set of information.

I know there's a __func__ variable containing the name of the current function as a string but not as a function pointer.

This is not to call the function then but just to be used as an index.

EDIT Basically what i would like to do is being able to run nested functions just before the execution of the current function (and also capturing the return to perform some things.) Basically, this is like __cyg_profile_func_enter and __cyg_profile_func_exit (the instrumentation functions)... But the problem is that these instrumentation functions are global and not function-dedicated.

EDIT In the linux kernel, you can use unsigned long kallsyms_lookup_name(const char *name) from include/linux/kallsyms.h ... Note that the CONFIG_KALLSYMS option must be activated.

12条回答
聊天终结者
2楼-- · 2019-01-18 05:13
#define FUNC_ADDR (dlsym(dlopen(NULL, RTLD_NOW), __func__))

And compile your program like

gcc -rdynamic -o foo foo.c -ldl
查看更多
倾城 Initia
3楼-- · 2019-01-18 05:14

Here's a trick that gets the address of the caller, it can probably be cleaned up a bit. Relies on a GCC extension for getting a label's value.

#include <stdio.h>

#define MKLABEL2(x) label ## x
#define MKLABEL(x) MKLABEL2(x)
#define CALLFOO do { MKLABEL(__LINE__): foo(&&MKLABEL(__LINE__));} while(0)

void foo(void *addr)
{
    printf("Caller address %p\n", addr);
}

int main(int argc, char **argv)
{
    CALLFOO;
    return 0;
}
查看更多
再贱就再见
4楼-- · 2019-01-18 05:15

No, the function is not aware of itself. You will have to build the table you are talking about yourself, and then if you want a function to be aware of itself you will have to pass the index into the global table (or the pointer of the function) as a parameter.

Note: if you want to do this you should have a consistent naming scheme of the parameter.

查看更多
狗以群分
5楼-- · 2019-01-18 05:15

Another option, if portability is not an issue, would be to tweak the GCC source-code... any volunteers?!

查看更多
Explosion°爆炸
6楼-- · 2019-01-18 05:15

If all you need is a unique identifier for each function, then at the start of every function, put this:

static const void * const cookie = &cookie;

The value of cookie is then guaranteed to be a value uniquely identifying that function.

查看更多
萌系小妹纸
7楼-- · 2019-01-18 05:17

If you want to do code generation I would recomend GSLGen from Imatix. It uses XML to structure a model of your code and then a simple PHP like top-down generation language to spit out the code -- it has been used to generate C code.

I have personally been toying arround with lua to generate code.

查看更多
登录 后发表回答