How to Get Function Name Inside a C++ Function

Get called function name as string

You need a C compiler that follows the C99 standard or later. There is a pre-defined identifier called __func__ which does what you are asking for.

void func (void)
{
printf("%s", __func__);
}

Edit:

As a curious reference, the C standard 6.4.2.2 dictates that the above is exactly the same as if you would have explicitly written:

void func (void)
{
static const char f [] = "func"; // where func is the function's name
printf("%s", f);
}

Edit 2:

So for getting the name through a function pointer, you could construct something like this:

const char* func (bool whoami, ...)
{
const char* result;

if(whoami)
{
result = __func__;
}
else
{
do_work();
result = NULL;
}

return result;
}

int main()
{
typedef const char*(*func_t)(bool x, ...);
func_t function [N] = ...; // array of func pointers

for(int i=0; i<N; i++)
{
printf("%s", function[i](true, ...);
}
}

Is it possible to get a function name without invoking it?

Unfortunately, not easily. C is not built for introspection and doesn't have features like this-- the name of function foo and the call to function foo are compiled down to just some jump and call instructions in the output; the actual name "foo" is essentially a convenience for you when programming and disappears in the compiled output.

The macro __FUNCTION__ is a preprocessor macro-- and as you note it only works within a function, because all it does it tell the preprocessor (as its churning through the text) hey, as you're scanning this token just drop in the name of the function you're currently scanning and then continue on. It's very "dumb" and is upstream of even the compiler.

There are various ways to get the effective result you want here, including most simply just manually building a table of string literals that have the same names as your functions. You can do this in fairly clean ways (see @nielsen's answer for a useful snippet) using macros. But the preprocessor/compiler can't help you derive or enforce a table from the actual functions so you will always have some risk of an issue at runtime when you make changes to it. Unfortunately C just doesn't have the capability for the kind of elegance you're looking for in this design.

C program to find the function name of a c file

I've used Simple C code to find the name of the function.

#include <stdio.h>
#include <string.h>

#define SIZE 1024
void ffname(char *line)
{
int i=1,j=0;
char *dt;
char name[SIZE];
strtok(line,"(");
dt = strchr(line,' ');
if(dt[i] == '*')
i++;
while(dt[i] != '\0')
{
name[j]=dt[i];
i++;
j++;
}
name[j] ='\0';
printf("Function name is: %s\n", name);
}

int main(int argc, char **argv)
{
if(argc < 2)
{
printf("Give the filename \n");
printf("Usage: %s filename\n", argv[0]);
return -1;
}
int i, lines =0, funlines =0,count =0, fn =0, flag =0;
char c[SIZE],b[SIZE];
FILE *fd;
fd = fopen(argv[1],"r");
while(fgets(c,SIZE,fd))
{
lines++;
i=0;
for(i=0;i<strlen(c);i++)
{
while( c[i] =='\t' || c[i] == ' ')
{
i++;
}
if( c[i] == '{')
{
count++;
if(flag)
{
funlines++;
}
if(count == 1)
{
fn++;
printf("Function %d is Started..............\n", fn);
flag = 1;
ffname(b);
}
break;
}
else if( c[i] == '}')
{
count--;
if(!count)
{
flag = 0;
printf("No of lines in the function %d is: %d\n", fn, funlines);
printf("Function %d is finished..........\n", fn);
funlines = 0;
}
else
{
funlines++;
}
break;
}
else if(flag)
{
funlines++;
break;
}
}
strcpy(b,c);
}
printf("Total no of function%d\n",fn);
printf("Total no of lines%d\n",lines);
return 0;
}

How can we know the caller function's name?

There's nothing you can do only in a.

However, with a simple standard macro trick, you can achieve what you want, IIUC showing the name of the caller.

void a()
{
/* Your code */
}

void a_special( char const * caller_name )
{
printf( "a was called from %s", caller_name );
a();
}

#define a() a_special(__func__)

void b()
{
a();
}

Using standard function name in C

One solution:

Now you have declaration of the function in some application .h file something like:

int getline(...); // the custon getline

Change that to:

int application_getline(...); // the custon getline
#define getline application_getline

I think that should do it. It will also fix the .c file where the function is defined, assuming it includes that .h file.

Also, use grep or "find in files" of editor to make sure that every place where that macro takes effect, it will not cause trouble.

Important: in every file, make sure that .h file included after any standard headers which may use getline symbol. You do not want that macro to take effect in those...

Note: this is an ugly hack. Then again, almost everything involving C pre-processor macros can be considered an ugly hack, by some criteria ;). Then again, getting existing incompatible code bases to co-operate and work together is often a case where a hack is acceptable, especially if long term maintenance is not a concern.

Note2: As per this answer and as pointed out in a comment, this is undefined behavior by C standard. Keep this in mind, if intention is to maintain the software for longer then just getting a working executable binary one time. But I added a better solution.

Is there a way to get function name inside a C++ function?

VC++ has

__FUNCTION__ for undecorated names

and

__FUNCDNAME__ for decorated names

And you can write a macro that will itself allocate an object and pass the name-yelding macro inside the constructor. Smth like

#define ALLOC_LOGGER FuncTracer ____tracer( __FUNCTION__ );

Lua C API: How to get a function name?

Lua values (function is just a value, like a number) has no names.

The function value that you find on stack is a result of expression evaluation, which could involve reading some variable (and probably you think that is a name of a function), or constructing new function in-place. On stack you get a result of expression, without possibly knowing which variable was read, if any at all.

If you really do need to have some unique name associated with the function, you must track those names/ids in your own table, accessible from the native side. Then you could easily lookup the name by the function value.

If it's not your code, but you still need to distinguish between functions, you can try to build that lookup table yourself, iterating the environment you want to monitor. That still can fail if environment is dynamically updated. Same variable can store any other function later.

But in general case - forget about the names, as values has no names.

What is the meaning in C when a function is in another function's name (not in the arguments)?

parse() is a function that returns a function pointer. You can use typedef with the type of the returned function to make it look a lot nicer, though:

#include <string.h>
#include <stdlib.h>

// parser_func describes a function that takes two ints and returns nothing
typedef void (*parser_func)(int, int);

// Like this one.
void somefunc(int a, int b) {}

// And parse() is a function that takes a char* and returns a
// pointer to a function that matches parser_func.
parser_func parse(char *op) {
if (!strcmp(op, "+"))
return somefunc;
else
return NULL;
}

int main(int argc, char *argv[]) {
int a;
int b;
parser_func fun; // Function pointer

if (argc == 4) {
a = atoi(argv[1]);
fun = parse(argv[2]); // Assign a function to fun
b = atoi(argv[3]);
if (fun) {
fun(a, b); // And call it if it's not null
}
}
return 0;
}


Related Topics



Leave a reply



Submit