Pointer to the current function

Is there a way to get a pointer to the current function, perhaps through gcc extensions or some other trickery?

Edit I'm curious if it is possible to get a pointer to a function without explicitly using the function name. I thought I had a good reason for this, I realized that I really was not, but I still wonder if this is possible.

+4
source share
4 answers

This is not particularly portable, but should work on at least some platforms (e.g. Linux and OSX, where I can check the documentation, it definitely does not work on Windows, which lacks an API):

#include <dlfcn.h> // ... void *handle = dlopen(NULL, RTLD_LAZY); void *thisfunction = handle ? dlsym(handle, __FUNCTION__) : NULL; if (handle) dlclose(handle); // remember to close! 

There are several other less portable shortcuts that work on some platforms, but not others. This is also not fast; cache it (for example, in a local variable static ) if you need speed.

+5
source

Not. In a three-letter answer. In C ++ member functions, you can have a "this" pointer that does something similar, but in C there is nothing equivalent.

However, since you cannot define anonymous functions, this function is not required.

+3
source

I understand that this is most likely not what you need ... but it still answers your question as it is currently worded:

 void someFunction() { void (*self)() = someFunction; } 

(Of course, here you can precisely use the identifier someFunction directly in most cases, instead of the function pointer self .)

If, however, you are looking for a way to do the same when you don’t know what the current function is called (how could you ever get into this situation, I wonder?), Then I don’t know the standard one that can transfer this method.

+2
source

It looks like this was asked earlier on SO, here is an interesting answer that I have not tested:

Get pointer to current function in C (gcc)?

Anyway, there are some interesting extensions, with gcc extensions, are you familiar with the __FUNCTION__ macro?

See what you think about it (this will just bring you a line with the name of the function:

 #include <stdio.h> #include <stdlib.h> void printme(char *foo) { printf("%s says %s\n", __FUNCTION__, foo); } int main(int argc, char *argv[]) { printme("hey"); return 0; } 
0
source

Source: https://habr.com/ru/post/1312915/


All Articles