4

Is it possible to get a pointer to the current function? If it is, how can I do so?

Motivation: I have a function doing some logging, and would like to call

log(currentfunc, "blabla")

Which does some output for example.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
musicmatze
  • 4,124
  • 7
  • 33
  • 48
  • you can get the function's name with a macro if you want for logging purposes in most compilers. _____func_____ is the macro if memory serves – Lefteris Sep 26 '12 at 13:21
  • See also here. http://stackoverflow.com/questions/2154852/get-a-pointer-to-the-current-function-in-c-gcc – md5 Sep 26 '12 at 13:45
  • 1
    Don't call your function `log` -- There's a commonly used function called `log` in math.h that returns the natural logarithm. – Douglas B. Staple Sep 26 '12 at 14:23
  • 1
    possible duplicate of: http://stackoverflow.com/questions/3048670/pointer-to-current-function and also http://stackoverflow.com/questions/2154852/get-a-pointer-to-the-current-function-in-c-gcc – Douglas B. Staple Sep 26 '12 at 14:25
  • Possible duplicate of [Get a pointer to the current function in C (gcc)?](https://stackoverflow.com/questions/2154852/get-a-pointer-to-the-current-function-in-c-gcc) – ShadowRanger Mar 19 '19 at 00:00

3 Answers3

5

You can obtain the name of the current function (but not a pointer to it) via the predefined identifier __func__ which is part of C99.

log(__func__, "blabla");

Here's the reference

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • Do you know a way to do it in c89? There's no need to do it in c89, but I would like to know it. – musicmatze Sep 26 '12 at 13:28
  • @cmusicmatze: No, in c89 the best you can do is use `__FILE__` and `__LINE__` or make use of non-standard possibilities your implementation offers, if any. – Armen Tsirunyan Sep 26 '12 at 13:29
  • @einpoklum: Not exactly. C++11 has `__FUNCTION__` which does the same. See http://stackoverflow.com/questions/15126387/func-c11-functions-local-predefined-variable-wont-compile – Armen Tsirunyan Mar 11 '14 at 12:46
  • @ArmenTsirunyan: IIANM, `__FUNCTION__` expands to a string, not an identifier. – einpoklum Mar 11 '14 at 13:23
  • @einpoklum: so does `__func__` in C99, doesn't it? You can't get a *pointer* to current function in either C or C++ – Armen Tsirunyan Mar 11 '14 at 13:27
2

I'm not sure about the pointer to a function, but the predefined identifier __func__ returns the name of the function. Maybe that can help...

In fact, I'd replace your function log with a macro so you don't have to paste in the name every time, as such:

#define log(x) log(__func__,x)
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

You can use combination of __FILE__ and __LINE__. It will be work with Microsoft and GCC compilers.

CAMOBAP
  • 5,523
  • 8
  • 58
  • 93