converting a variable name to a string in C++ - c++

I'd like to output some data to a file. For example assume I have two vectors of doubles:
vector<double> data1(10);
vector<double> data2(10);
is there an easy way to output this to a file so that the first row contains the headings 'data1' and 'data2' followed by the actual contents. The function which
outputs the data will be passed various different arrays so hardcoding the name
of the heading is not possible - ideally I'd like to convert the variable name
to some string and then output that string followed by the contents of the vector array. However, I'm not sure how to convert the variable name 'data1' to a string,
or indeed if it can easily be done (from reading the forums my guess is it can't)
If this is not possible an alternative might be to use an associative
container such as map or perhaps more simply a 'pair' container.
pair<vector<double>,string> data1(10,'data1');
Any suggestions would be welcome!

You can use the preprocessor "stringify" # to do what you want:
#include <stdio.h>
#define PRINTER(name) printer(#name, (name))
void printer(char *name, int value) {
printf("name: %s\tvalue: %d\n", name, value);
}
int main (int argc, char* argv[]) {
int foo = 0;
int bar = 1;
PRINTER(foo);
PRINTER(bar);
return 0;
}
name: foo value: 0
name: bar value: 1
(Sorry for printf, I never got the hang of <iostream>. But this should be enough.)

try this:
#define GET_VARIABLE_NAME(Variable) (#Variable)
//in functions
int var=0;
char* var_name= GET_VARIABLE_NAME(var);

I had the same problem. After a little bit of experimentation I created following macros that convert names of variables, fields, functions, methods and types to strings.
#define MACRO_VARIABLE_TO_STRING(Variable) (void(Variable),#Variable)
#define MACRO_FUNCTION_TO_STRING(Function) (void(&Function),#Function)
#define MACRO_METHOD_TO_STRING(ClassName,Method) (void(&ClassName::Method),#Method)
#define MACRO_TYPE_TO_STRING(Type) (void(sizeof(Type)),#Type)
The code uses comma operator and void conversion to force compiler to check if variable, function, etc. really exists. The nice thing is that it works well with uninitialized variables too. I tested it on both VC and GCC with all pedantic options I found out without any warning messages.
int GetAndPrintValue(const char* VariableName)
{
std::cout << VariableName << std::endl;
return 10;
}
int Variable=GetAndPrintValue(MACRO_VARIABLE_TO_STRING(Variable));
I use such code when I write parsers that reads data from input stream and if parsed variable is out of bounds it throws an exception with name of variable that failed my validity checks.

Slightly adapted from #sarnold's answer, for C++:
#define DEBUG(x) std::cout << #x << " = " << x << std::endl;
An example program which uses this:
int main() {
int foo = 1;
DEBUG(foo);
return 0;
}

You can use the preprocessor, there's a stringify token, but it's only available from the source, not to a function (you'd get the argument name).

I had a similar quest. In Qt, I got tired of constantly writing the variable name as a string without autocomplete when writing to qDebug().
After a lot of trial and error with different macros and functions, I found that this macro works great:
#define PRINT(x) ", " << #x << ": " << x
Example usage:
int someVariable = 42;
double anotherVariable = 13.37;
qDebug().nospace() << "Some text" << PRINT(someVariable) << PRINT(anotherVariable);
Output:
Some text, someVariable: 42, anotherVariable: 13.37
I guess this (or something very similar) will work for std::cout as well.
A bit late to the party, but I hope this can help anyone out there!

I'd have thought the obvious answer is to make the function that performs the output take the heading text as a string parameter.

For this case I have made nameof() macro. It returns a std::string name of a variable, type or member. It works like nameof() in C#.
For Example:
#include "nameof.h"
std::vector<double> data1(10);
std::string name = nameof(data1); // "data1"
struct Foo1
{
struct Foo2
{
Foo1* foo1;
};
Foo1* foo1;
Foo2 foo2;
};
name = nameof(Foo1::foo1->foo2.foo1); // "foo1"
name = nameof(123); // std::logic_error exception

Related

c++ converting unknown struct to string

i have a question. Is it possible to get all data types and the variable names from a struct? For example:
void func(void *p){
std::cout << "p->type_1" << ... << "p->type_x" << std::endl;
std::cout << "p->name_1" << ... << "p->name_x";}
typedef struct{
int a;
char b;
float c;
}test;
test a;
func(&a);
//There should come something like
"int char float"
"a b c"
Not directly, an X-Macro can help but this is really really ugly:
#include <stdio.h>
#define TEST \
X(int a;) \
X(char b;) \
X(float c;)
typedef struct {
#define X(x) x
TEST
#undef X
} test;
void print()
{
#define X(x) puts(#x);
TEST
#undef X
}
int main(void)
{
print();
return 0;
}
Output:
int a;
char b;
float c;
For this to work, you would need support for introspection in C++, and runtime type information. Some languages have this built in, but C++ does not (well, not enough for this purpose).
Depending on your needs, you could build information about your struct's data types and pass a pointer to that information along with that struct pointer into your function. Useful tools for this might be the typeid operator, the offsetof macro, the typeof macro, and the C preprocessor with its stringify operator (#).
With those you should be able to build an array that contains a field's name, something that identifies what primitive type it has, and at what offset in the void* it can be found. You might have some more work if you need to also support fields of other struct types (basically you'd need to embed their fields into that structure, or reference it.
That said, there might be better, easier ways to do this depending on what you need this output for and how much control you have over your code and the structs you want to print.
For example, most debuggers can print structs using platform-specific debug metadata, so you might not need this approach if you're just trying to improve your debug experience (this information is often in separate files and contains many other things, so isn't suitable for use outside debugging).
Alternately, if you can modify the classes (in C++ classes and structs are the same thing) you get, you could give them all a common base class and a print() method. Then each struct would know how to print itself, and you could just call that.
There might be other solutions if you can use, but it depends on why you need this and who controls the classes you're trying to print and why. E.g. Object graph serialization tools etc.
It is not possible to retrive from struct.
From the variable , u can get:
int a= 5;
cout << "a has type: " << typeid(a).name()
Output : int
If it's a struct, all fields are public so nothing prevent you to do std::cout << typeid(p->a) << typeid(p->b) << std::endl; std::cout << p->a << p->b << endl

Calling a function using a string containing the function's name

I have a class defined as
class modify_field
{
public:
std::string modify(std::string str)
{
return str;
}
};
Is there any way to store this function name inside a string in main function and then call it.
I tried this but it's not working.
int main()
{
modify_field mf;
std::string str,str1,str2;
str = fetch_function_name(); //fetch_function_name() returns string modify
str2 = "check";
cout << str; //prints modify
str1 = str + "(" +str2 + ")";
mf.str1();
}
I know this is wrong. But I just want to know if there is any way to call a function name using variable.
This is not directly possible in C++. C++ is a compiled language, so the names of functions and variables are not present in the executable file - so there is no way for the code to associate your string with the name of a function.
You can get a similar effect by using function pointers, but in your case you are trying to use a member function as well, which complicates matters a little bit.
I will make a little example, but wanted to get an answer in before I spend 10 minutes to write code.
Edit: Here's some code to show what I mean:
#include <algorithm>
#include <string>
#include <iostream>
#include <functional>
class modify_field
{
public:
std::string modify(std::string str)
{
return str;
}
std::string reverse(std::string str)
{
std::reverse(str.begin(), str.end());
return str;
}
};
typedef std::function<std::string(modify_field&, std::string)> funcptr;
funcptr fetch_function(std::string select)
{
if (select == "forward")
return &modify_field::modify;
if (select == "reverse")
return &modify_field::reverse;
return 0;
}
int main()
{
modify_field mf;
std::string example = "CAT";
funcptr fptr = fetch_function("forward");
std::cout << "Normal: " << fptr(mf, example) << std::endl;
fptr = fetch_function("reverse");
std::cout << "Reverse: " << fptr(mf, example) << std::endl;
}
Of course, if you want to store the functions in a map<std::string, funcptr>, then that is entirely possible.
You have two choices:
1 - manually create a map with pointers to the functions you need and their identifiers as a string key so you can perform lookups, or..
2 - create a dynamic link library/shared object and use name lookup to get the pointer. Use extern "C" to prohibit identifier mangling. You may not be able to use certain C++ features and performance will be slightly worse, depending on your actual usage scenario.
It surely possible with C functions, but will be really tricky and unportable for C++ - because different OSes (and even different compilers on the same OS) uses different ABIs for C++, so real function names differ quite significantly from what you named them in your code.
If C functions is ok (e.g. you can declare them as extern "C"), you can use dlsym for POSIX OSes and GetProcAddress for windows. Of course, you'll need to add this functions into dynamic symbols table - something like '-rdynamic' flag for ld, or __declspec(dllexport) (hope that was right - haven't used if for a long time) on windows.
If the functions have same signature you can create a map of string to std::function objects. See more about std::function here: std::function
Maybe a pointer to this function is more adequate. It allows you to easily chose between functions to call:
#include<iostream>
using namespace std;
class modify_field
{
public:
std::string modify_1(std::string str)
{
return str;
}
std::string modify_2(std::string str)
{
return str + str;
}
};
int main()
{
string (modify_field::* fun_ptr) (string) = &modify_field::modify_1;
modify_field m;
cout << (m.*fun_ptr)("test") << endl;
fun_ptr = &modify_field::modify_2;
cout << (m.*fun_ptr)("test") << endl;
}
If you placed all the functions that you would like to lookup by name in a set of source files that you then generate a DLL with, you could use the dlopen() and dlsym() functions to find the entry point.
An example of how to do this can be found in the man pages of dlsym() on your machine, or you could refer to this link.
This only works well on functions that are unmangled (i.e. with C++ you may have some issues). You may either have to define these entry points as "extern C" to prevent mangling, or come up with some other mechanism to guess the mangled name for a C++ entry point. I have never done the latter so there are bound to be some nuances there that I'm oblivious to.
If you are using Windows (wasn't clear what OS you are on), you should lookup the documentation of GetProcAddress() which is available online here.
A good tutorial on the subject in general, and this one does talk about how to do all this with C++ can be found here.

Modify log class to accept variables in string - C++

I am trying to modify my log class to accept variables in my string. For example, if I wanted to output that there are 7 players in an area.
Here is my write to log function:
void Log::writeSuccess(string text,...)
{
// Write the sucessfull operation to the logfile
logfile << "<---> " << text << endl;
}
And here is my calling code:
int playernum = 7;
errorLog.writeSuccess("There are %i players in the area", playernum);
It just ends up outputting to the file: There are %i players in the area
Any way to fix this?
I wonder how on earth does your program even compile?!
You call writeSuccess with 2 arguments, whereas it is declared to take only one argument.
You should look at boost format
The problem with using printf-style format strings is that those strings are
dependent on the types of the provided arguments, and
dependent on the order of the provided arguments.
Not only is this error-prone when you are writing those lines. In my experience the types and order of the arguments will easily change in software that is actively maintained and extended, and it's much harder still to keep the format strings in sync with changes applied later, than it is to do so when you initially write the code.
The problem of needing to manually keep the parameter types in sync with the format string can easily be solved in C++, streams have proven that 25 years ago. Boost.Format even manages to combine format strings with type safety.
A different approach, solving both problems, is taken by some logging libraries I have seen: They use a syntax where you specify which parameter is to be inserted at a specific place in a string by using the parameter's name, and they free you from having to think about the parameter's type by individually converting all parameters to strings before inserting them:
log( "i now has the value of #(i), current size is #(x.get_size(y))",
LOG_PARAM(i) + LOG_PARAM(x.get_size(y)) );
If you don't want to use stdarg.h which doesn't look good in c++ IMO. you can do something like this. Keep in mind that although this is a small class (you can add to it for better logging), its not the most efficient way to do it.
#include <iostream>
#include <sstream>
class Log
{
public:
Log() : os()
{
}
~Log()
{
fprintf(stderr, "%s\n", os.str().c_str());
}
template<typename T>
std::ostringstream &operator<<(const T &t)
{
os << "Log file - " << t;
return os;
}
private:
std::ostringstream os;
};
int main(int argc, char *argv[])
{
//usage
for (int i = 0; i < 10; ++i)
Log() << "Hello world " << i;
return 0;
}
Look at stdarg standard library. It allows you to handle variable number of parameters.
In case you can't or won't use boost:
void Log::writeSuccess(const char* const fmt, ...) {
va_list ap;
va_start(ap, fmt);
char buff[1024];
vsnprintf(buff, sizeof(buff), fmt, ap);
logfile << buff;
}
Note: it assumes that the written length is limited.
Update: with gcc it's possible to do this in a type-safe way, you need the following declaration.
class Log {
void writeSuccess(const char* const fmt, ...) __attribute__ ((format (printf, 2, 3)));
//...
};
Info here. Note: it's a warning, not a compile error. If you ignore warnings that's your problem..:)

C++ Pointers help?

I need a little bit of help with using pointers in C++. Sorry to seem beginner but I really can't quite understand them. I have read the tutorial on pointers on the cplusplus.com website, so please don't suggest that.
I basically have a variable which holds the name of another variable, and I wish to access that variable through the holder one. I believe I need to use pointers, correct me if I'm wrong though.
E.g.
int a;
string b;
a = 10;
b = "a";
I need to access the variable "a" through the contents of variable "b".
Just to put this into better perspective, this is how I am using it:
int a;
a = 20;
void getVar(string name) {
cout << name;
}
getVar("a");
But as you can see, on the fifth line, that will just cout the value of name, in this case "a", but I want it to cout the value of the variable which name contains, so I want it to output "20".
Any help here would be much appreciated.
If you need to associate a name with a value, consider associative arrays otherwise known as dictionaries and maps. The Standard Template Library has std::map that you can use to associate text with a value:
#include <map>
#include <string>
std::map<std::string, int> my_map;
my_map["A"] = 20;
cout << my_map["A"] << endl;
What you are thinking of is called (Reflection) which C++ does not support. You can however use pointers to access what is in a variable it points to:
int a = 5; //int variable that stores 5
int *b = &a; //int pointer that stores address of a
(*b) = 10; //stores 10 into address that b points to (a)
cout << a; //prints 10
What you are trying to achieve is not possible in a compiled language (not considering reflection). You might accomplish something similar using a map data structure.
theMap["a"] = 20;
and a corresponding
void getVar(string key){
cout << theMap[key];
}
that can be called with
getVar("a");
Note that in this extremely simple sample theMap has to be in scope for the function, like in a class or a namespace.
If you use pointers you are just using a level of indirection not at all suited for your example. See Chads answer for instance.
Theres no real way for you to access variables by name like that unless you create some kind of container class that has a name member that you look up by. I'm not sure what this has to do with pointers though.
What you're asking for is called "reflection" or "introspection" - the ability to use design-time names for your program's objects (classes, variables, functions, etc) in run time. C++ does not support that out of the box - the design-time names are stripped upon compilation.
There are some libraries that provide that capability in C++; but there are also languages where reflection is is part of the language. Python or JavaScript, for example.
Maybe this could suit you:
int a = 5;
class b {
public:
b(int &x) { ref_ = x; }
int operator()(void) { return ref_; }
private:
int &ref_;
}
b my_b(a);
my_b() /* -> 5 */;
Your code does not use pointers. you're trying to convert a string into an identifier and print it's result, I don't know whether that's possible or not. If you intended using pointer your code should've looked like this:
int a = 20;
int* b = &a;
cout << *b;
quick fix for outputting integers only:
int a;
a = 20;
void getVar(int name) {
cout << name;
}
getVar(a);
If you need the function to work for any type of variable, maybe think about some template function.
Edit: Here is the code for the template program:
#include <iostream>
#include <string>
using namespace std;
template <class T>
void getVar(T name){
cout<<name<<endl;
}
int main()
{
string x="hee";
int y=10;
getVar(x);//outputs hee
getVar(y);//outputs 10
return 0;
}

How do I find the name of the calling function?

I have been using PRETTY_FUNCTION to output the current function name, however I have reimplemented some functions and would like to find out which functions are calling them.
In C++ how can I get the function name of the calling routine?
Here is a solution you can often use. It has the advantage of requiring no changes to the actual function code (no adding calls to stackwalk functions, changing parameters to pass in function names, or linking to extra libraries.). To get it working, you simply need to use a bit of preprocessor magic:
Simple Example
// orignal function name was 'FunctionName'
void FunctionNameReal(...)
{
// Do Something
}
#undef FunctionName
#define FunctionName printf("Calling FunctionName from %s\n",__FUNCTION__);FunctionNameReal
You must rename your function temporarily, but see the note below for more suggestions. This will result in a printf() statement at each point of calling the function. Obviously, you have to make some arrangements if you are calling a member function, or need to capture the return value (Like pass the function call and __FUNCTION__ to a custom function that returns the same type...), but the basic technique is the same. You might want to use __LINE__ and __FILE__ or some other preprocessor macros depending on which compiler you have. (This example is specifically for MS VC++, but probably works in others.)
Also, you might want to put something like this in your header surrounded by #ifdef guards to conditionally turn it on, which can handle renaming the actual function for you as well.
UPDATE [2012-06-21]
I got a request to expand my answer. As it turns out, my above example is a bit simplistic. Here are some fully compiling examples of handling this, using C++.
Full Source Example with a return value
Using a class with operator() makes this pretty straight forward. This first technique works for freestanding functions with and without return values. operator() just needs to reflect the same return as the function in question, and have matching arguments.
You can compile this with g++ -o test test.cpp for a non-reporting version and g++ -o test test.cpp -DREPORT for a version that displays the caller information.
#include <iostream>
int FunctionName(int one, int two)
{
static int calls=0;
return (++calls+one)*two;
}
#ifdef REPORT
// class to capture the caller and print it.
class Reporter
{
public:
Reporter(std::string Caller, std::string File, int Line)
: caller_(Caller)
, file_(File)
, line_(Line)
{}
int operator()(int one, int two)
{
std::cout
<< "Reporter: FunctionName() is being called by "
<< caller_ << "() in " << file_ << ":" << line_ << std::endl;
// can use the original name here, as it is still defined
return FunctionName(one,two);
}
private:
std::string caller_;
std::string file_;
int line_;
};
// remove the symbol for the function, then define a new version that instead
// creates a stack temporary instance of Reporter initialized with the caller
# undef FunctionName
# define FunctionName Reporter(__FUNCTION__,__FILE__,__LINE__)
#endif
void Caller1()
{
int val = FunctionName(7,9); // <-- works for captured return value
std::cout << "Mystery Function got " << val << std::endl;
}
void Caller2()
{
// Works for inline as well.
std::cout << "Mystery Function got " << FunctionName(11,13) << std::endl;
}
int main(int argc, char** argv)
{
Caller1();
Caller2();
return 0;
}
Sample Output (Reporting)
Reporter: FunctionName() is being called by Caller1() in test.cpp:44
Mystery Function got 72
Reporter: FunctionName() is being called by Caller2() in test.cpp:51
Mystery Function got 169
Basically, anywhere that FunctionName occurs, it replaces it with Reporter(__FUNCTION__,__FILE__,__LINE__), the net effect of which is the preprocessor writing some object instancing with an immediate call to the operator() function. You can view the result (in gcc) of the preprocessor substitutions with g++ -E -DREPORT test.cpp. Caller2() becomes this:
void Caller2()
{
std::cout << "Mystery Function got " << Reporter(__FUNCTION__,"test.cpp",51)(11,13) << std::endl;
}
You can see that __LINE__ and __FILE__ have been substituted. (I'm not sure why __FUNCTION__ still shows in the output to be honest, but the compiled version reports the right function, so it probably has something to do with multi-pass preprocessing or a gcc bug.)
Full Source Example with a Class Member Function
This is a bit more complicated, but very similar to the previous example. Instead of just replacing the call to the function, we are also replacing the class.
Like the above example, you can compile this with g++ -o test test.cpp for a non-reporting version and g++ -o test test.cpp -DREPORT for a version that displays the caller information.
#include <iostream>
class ClassName
{
public:
explicit ClassName(int Member)
: member_(Member)
{}
int FunctionName(int one, int two)
{
return (++member_+one)*two;
}
private:
int member_;
};
#ifdef REPORT
// class to capture the caller and print it.
class ClassNameDecorator
{
public:
ClassNameDecorator( int Member)
: className_(Member)
{}
ClassNameDecorator& FunctionName(std::string Caller, std::string File, int Line)
{
std::cout
<< "Reporter: ClassName::FunctionName() is being called by "
<< Caller << "() in " << File << ":" << Line << std::endl;
return *this;
}
int operator()(int one, int two)
{
return className_.FunctionName(one,two);
}
private:
ClassName className_;
};
// remove the symbol for the function, then define a new version that instead
// creates a stack temporary instance of ClassNameDecorator.
// FunctionName is then replaced with a version that takes the caller information
// and uses Method Chaining to allow operator() to be invoked with the original
// parameters.
# undef ClassName
# define ClassName ClassNameDecorator
# undef FunctionName
# define FunctionName FunctionName(__FUNCTION__,__FILE__,__LINE__)
#endif
void Caller1()
{
ClassName foo(21);
int val = foo.FunctionName(7,9); // <-- works for captured return value
std::cout << "Mystery Function got " << val << std::endl;
}
void Caller2()
{
ClassName foo(42);
// Works for inline as well.
std::cout << "Mystery Function got " << foo.FunctionName(11,13) << std::endl;
}
int main(int argc, char** argv)
{
Caller1();
Caller2();
return 0;
}
Here is sample output:
Reporter: ClassName::FunctionName() is being called by Caller1() in test.cpp:56
Mystery Function got 261
Reporter: ClassName::FunctionName() is being called by Caller2() in test.cpp:64
Mystery Function got 702
The high points of this version are a class that decorates the original class, and a replacement function that returns a reference to the class instance, allowing the operator() to do the actual function call.
With GCC version ≥ 4.8 you can use __builtin_FUNCTION — not to be confused with __FUNCTION__ and similar — it seems to be a bit obscure.
Example:
#include <cstdio>
void foobar(const char* str = __builtin_FUNCTION()){
std::printf("called by %s\n", str);
}
int main(){
foobar();
return 0;
}
output:
called by main
example on WandBox
Here are two options:
You can get a full stacktrace (including the name, module, and offset of the calling function) with recent versions of glibc with the GNU backtrace functions. See my answer here for the details. This is probably the easiest thing.
If that isn't exactly what you're looking for, then you might try libunwind, but it's going to involve more work.
Keep in mind that this isn't something you can know statically (as with PRETTY_FUNCTION); you actually have to walk the stack to figure out what function called you. So this isn't something that's really worth doing in ordinary debug printfs. If you want to do more serious debugging or analysis, though, then this might be useful for you.
Unless there is more to the question than you explicitly asked, just rename the function and let the compiler/linker tell you where it is called.
Variation of Aaron answer. I am not sure whether this answer has this problem, but when you do a #define function, it becomes a global variable, then, if your project has several classes with the same member class function name, all classes will have their function name redefined to the same function.
#include <iostream>
struct ClassName {
int member;
ClassName(int member) : member(member) { }
int secretFunctionName(
int one, int two, const char* caller, const char* file, int line)
{
std::cout << "Reporter: ClassName::function_name() is being called by "
<< caller << "() in " << file << ":" << line << std::endl;
return (++member+one)*two;
}
};
#define unique_global_function_name(first, second) \
secretFunctionName(first, second, __FUNCTION__,__FILE__,__LINE__)
void caller1() {
ClassName foo(21);
int val = foo.unique_global_function_name(7, 9);
std::cout << "Mystery Function got " << val << std::endl;
}
void caller2() {
ClassName foo(42);
int val = foo.unique_global_function_name(11, 13);
std::cout << "Mystery Function got " << val << std::endl;
}
int main(int argc, char** argv) {
caller1();
caller2();
return 0;
}
Result:
Reporter: ClassName::function_name() is being called by caller1() in D:\test.cpp:26
Mystery Function got 261
Reporter: ClassName::function_name() is being called by caller2() in D:\test.cpp:33
Mystery Function got 702
In the firs approximation, just grep the codebase for the function names. Then comes Doxygen, and then dynamic logging (both discussed by others).
You can use this code, to track loci of control in last n points in your program. Usage: see main function below.
// What: Track last few lines in loci of control, gpl/moshahmed_at_gmail
// Test: gcc -Wall -g -lm -std=c11 track.c
#include <stdio.h>
#include <string.h>
#define _DEBUG
#ifdef _DEBUG
#define lsize 255 /* const int lsize=255; -- C++ */
struct locs {
int line[lsize];
char *file[lsize];
char *func[lsize];
int cur; /* cur=0; C++ */
} locs;
#define track do {\
locs.line[locs.cur]=__LINE__ ;\
locs.file[locs.cur]=(char*)__FILE__ ;\
locs.func[locs.cur]=(char*) __builtin_FUNCTION() /* __PRETTY_FUNCTION__ -- C++ */ ;\
locs.cur=(locs.cur+1) % lsize;\
} while(0);
void track_start(){
memset(&locs,0, sizeof locs);
}
void track_print(){
int i, k;
for (i=0; i<lsize; i++){
k = (locs.cur+i) % lsize;
if (locs.file[k]){
fprintf(stderr,"%d: %s:%d %s\n",
k, locs.file[k],
locs.line[k], locs.func[k]);
}
}
}
#else
#define track do {} while(0)
#define track_start() (void)0
#define track_print() (void)0
#endif
// Sample usage.
void bar(){ track ; }
void foo(){ track ; bar(); }
int main(){
int k;
track_start();
for (k=0;k<2;k++)
foo();
track;
track_print();
return 0;
}
You probably want the names of all functions that potentially could call them. This is basically a set of edges in the call graph. doxygen can generate the call graph, and then it's simply a matter of looking at the incoming edges of your functions node.
Combining __builtin_return_address and dladdr works in C++, C, Objective-C and Objective-C++:
#include <dlfcn.h>
Dl_info info;
if (dladdr(__builtin_return_address(0), &info)) {
printf("%s called by %s", __builtin_FUNCTION(), info.dli_sname);
}
Note that dladdr requires a dynamically linked programs:
To link your program dynamically, you might need to add -rdynamic or -Wl,--export-dynamic as an option (source).
Cflow can be used to get the call graph of the source code written in C/C++. You can parse this call graph to get what you want.