I've read posts/articles about lambdas, function pointers, anonymous functions in general and other related things but nothing I've seen (I think) has hit on exactly what I'm looking to do.
It seems like accomplishing this should be pretty simple, but say I have a function containing things I always want to do when called, but each time I call it I want it to run a function I describe (and only need to use once) in the argument (this anonymous function being the only argument).
Assuming this function which accepts my anonymous function as its argument is in main.cpp so it's called from main is it possible to implement this in a simple way?
Basically I'm trying to figure out the syntax in C++ for going from this:
// Some function with partially duplicated code
void OriginalA()
{
DoThingsA();
// unique code
DoThingsB();
}
// Another function with partially duplicated code
void OriginalB()
{
DoThingsA();
// unique code
DoThingsB();
}
To this:
// Encapsulate shared functionality
// <param name="action">User defined action</param>
void UniqueWrapper(Action action)
{
DoThingsA();
action();
DoThingsB();
}
// New implmentation of A
void NewA()
{
UniqueWrapper(() =>
{
// unique code
});
}
// New implementation of B
void NewB()
{
UniqueWrapper(() =>
{
// unique code
});
}
Which I found as #1 here: http://www.wildbunny.co.uk/blog/2012/11/01/10-steps-to-becoming-a-better-programmer/
But a setup like this where literally all you would have to do for the call is:
theFunctionName(() => { /*unique things to do*/ });
If this ^^ is legal calling syntax then I'm just not sure how the parameter looks in the definition of theFunctionName, clearly it isn't (Action action) like in the example above.
Replace the Action argument with:
template<typename Function>
void UniqueWrapper(Function action) {
DoThingsA();
action(); // call the passed in function
DoThingsB();
};
Call it like this:
void NewA() {
UniqueWrapper([]() {});
// ^^^^^^^
// C++11 lambda syntax
}
Instead of a lambda you can also use function pointers, member functions (using std::mem_fn), or functors. Every kind of callable object will work.
There are multiple ways to do this, but not all will work on all platforms (e.g. because they'd require C++11 features (lambdas).
The more classic approach would be something like this (without an anonymous function):
#include <iostream>
typedef void(*Action)();
void UniqueWrapper(Action action) {
std::cout << "Generic Code 1" << std::endl;
action();
std::cout << "Generic Code 2" << std::endl;
}
void CustomAction(void) {
std::cout << "Custom Code" << std::endl;
}
int main(int argc, char **argv) {
UniqueWrapper(&CustomAction);
return 0;
}
Of course you could use some macro shenanigans to make this more "dynamic".
Once you accept C++11 code as well (which is required to have lambdas as explained), you can do something like this:
#include <iostream>
typedef void(*Action)();
void UniqueWrapper(Action action) {
std::cout << "Generic Code 1" << std::endl;
action();
std::cout << "Generic Code 2" << std::endl;
}
int main(int argc, char **argv) {
UniqueWrapper([](){
std::cout << "Custom Code" << std::endl;
});
return 0;
}
Of course, there's room for more changes, for example you could use std::function rather than a function pointer.
Related
I must be misunderstanding something because I thought the two cases are the same:
#include <iostream>
void function() { std::cout << "Hi\n"; }
int main()
{
std::vector<void(*)()> funcPtrVec;
std::vector<void()> funcVec;
funcPtrVec.push_back(function); // Works
funcVec.push_back(function); // Works
auto lambdaFunc = []() { std::cout << "Hi\n"; };
funcPtrVec.push_back(lambdaFunc); // Works
funcVec.push_back(lambdaFunc); // Doesn't work
}
Now, in both cases my compiler says that the function signatures are the same, void function() and void lambdaFunc(). I really thought that when a lambda function doesn't capture anything it behaves like a free function, which the same signatures would seem to support. Also, I guess I'm confused even more due to the fact that in the following all seem to be treated the same, as if decaying to the same thing:
void function() { std::cout << "Hi\n"; }
void funcTakingFunc(void()) {}
void funcTakingFuncPtr(void(*)()) {}
int main()
{
auto lambdaFunc = []() { std::cout << "Hi\n"; };
void(*funcPtr)() = lambdaFunc; // Works
funcTakingFuncPtr(lambdaFunc); // Works
funcTakingFuncPtr(funcPtr); // Works
funcTakingFunc(lambdaFunc); // Works
funcTakingFunc(funcPtr); // Works
// They all work
}
So as far as I can see the only distinction between the function and the function pointer made is when given as a template argument to vector. This obviously means I don't understand templates well, but what's the reason for this? Because the two really seem the same from the examples I tried.
std::vector<void()> is not allowed; the type must be an object type, and a function type is not an object type.
There are various parts of the specification of vector requirements we could identify as being violated by a non-object type; the most obvious is the default allocator. In the table in [allocator.requirements]/2 it is specified that the type the allocator is for must be an object type.
I wonder if it is possible to do this in C ++?
e.g:
varFunction = void TestFunction();
RunCode(varFunction);
With C++11 and higher, you can use the std::function to store function pointers and function objects.
But storing function pointers was available in C++ from the start. This means you can store the address of a function and call it later.
BTW, lambda expressions are also very useful (and the closure they are denoting could be assigned or passed as std::function-s)
Here is an example showing three different ways to achieve what did you asked for:
#include <iostream>
#include <functional>
void RunCode(const std::function<void()>& callable) {
callable();
}
void TestFunction() {
std::cout << "TestFunction is called..." << std::endl;
}
int main() {
std::function<void()> varFunction_1 = TestFunction;
void (*varFunction_2)() = TestFunction;
RunCode(varFunction_1);
RunCode(varFunction_2);
RunCode([]() { std::cout << "TestLambda is called..." << std::endl; });
return 0;
}
But this is just the tip of the iceberg, passing function pointers and function objects as parameters is very common in the algorithms library.
C++ provides several ways to do it.
For example, you can use std::function template: include <functional> and use the following syntax (demo):
std::function<void()> varFunction(TestFunction);
varFunction();
You can also use function pointers (Q&A on the topic).
For the sake of completeness, you can declare a C-style function type as follows:
typedef int (*inttoint)(int);
This creates a type inttoint that can store any function that takes an int as parameter and returns an int. You can use it as follows.
// Define a function
int square(int x) { return x*x; }
// Save the function in sq variable
inttoint sq { square };
// Execute the function
sq(4);
Since C++11, these variables can also store lambda functions, like so
inttoint half { [](int x) { return x/2; } };
And use it same as above.
The easiest way is to use a lambda expression like this:
auto add = [](int a, int b) { return a+b; };
cout << add(10, 20) << endl; // Output: 30
More info about how lambda expressions work: http://en.cppreference.com/w/cpp/language/lambda
Here is a sample design code of what I want to achieve. Basically I wanna store handler functions for different handlerNames and these handler functions can be of variable arguments.
The handler functions should be called on events with the required arguments are passed with Script::Handle(...)
How can I achieve this? Maybe its possible with Variadic Templates?
class Script
{
public:
Script() { /* ... */ }
template<typename TFunction>
void AddHandler(const char *handlerName, TFunction &&function)
{
_handlerMap[handlerName] = std::move(function);
}
void Handle(const char *handlerName, ...)
{
_handlerMap[handlerName](...);
}
private:
typedef std::map<std::string, std::function<void()>> HandlerMapType;
HandlerMapType _handlerMap;
};
//Handler functions
handlerOne() { std::cerr << "One"; }
handlerTwo(std::string a1, int a2) { std::cerr << "Two"; }
handlerThree(bool a1) { std::cerr << "Three"; }
int main(int argc, char **argv)
{
Script script;
script.AddHandler("One", std::bind(&handlerOne));
script.AddHandler("Two", std::bind(&handlerTwo));
script.AddHandler("Three", std::bind(&handlerThree));
script.Handle("One");
script.Handle("Two, "string", 96);
script.Handle("Three", true);
script.Handle("Three", "what should happen here?"); //String passed instead of bool
}
Let me prefix by saying that this is not a trivial thing to do in C++. And I will go as far to say that you should consider whether this is really something you need in your use case. In your example, you are asking for genericism that you can't really use. You will in any case need to know the signature of the function you are calling to call it properly; in that case what purpose is served by putting them in a container?
Generally, you'd do something like this if you are writing a middle layer of code. In your example, this would be equivalent to writing code that enables another user to call Handle. A common concrete example of this is to write a factory where objects in the factory may be instantiated using different arguments. However, it can't really be "different" arguments, at least not without some crazy casting. The solution is to make all the functions take the same argument, but make the argument a dynamic type that can store whatever arguments you want:
using argument_type = std::unordered_map<std::string, boost::any>;
void print(const argument_type & arg) {
auto to_print = boost::any_cast<std::string>(arg["to_print"]);
std::cerr << to_print << std::endl;
}
void print_none(const argument_type & arg) {
std::cerr << "none" << std::endl;
}
using my_func_t = std::function<void(const argument_type &)>;
std::vector<my_func_t> v;
v.emplace_back(print);
v.emplace_back(print_none);
// create some argument_types, feed them to f.
The above is not code that has been tested, nor with a working main, but I think this should give you a sense of how you could accomplish what you want.
edit: I thought about it a bit more, and I decided to elaborate a bit more on the "crazy casting" way. I suppose it's not really more crazy, but I strongly prefer what I showed above. The alternative is to completely type erase the functions themselves, and pass the arguments using a variadic template.
void print(std::string to_print) {
std::cerr << to_print << std::endl;
}
void print_none() {
std::cerr << "none" << std::endl;
}
std::vector<boost::any> v;
v.emplace_back(std::function<void(std::string)>(print));
v.emplace_back(std::function<void(void)>(print_none));
template <typename ... Args>
void call(const std::vector & funcs, int index, Args... args) {
auto f = boost::any_cast<std::function<void(Args...)>>(funcs[index]);
f(std::forward<Args>(args)...);
}
// unsure if this will actually work
call(f, 0, std::string("hello"));
The code above is very fragile though, because the types you pass to call will be deduced against, and then the cast will try to cast to a std::function that matches that signature. That exact signature. I don't have a lot of confidence that this will work out; if it's a reference, vs value, vs rvalue, etc. Casting back to a different std::function than what you put in is undefined behavior.
In summary, I'd either try to avoid needing to do this entirely, or go with the first solution. It's much less fragile, and it's better to be upfront about the fact that you are erasing the signatures of these functions.
I am trying to use the function signal(int,void(*)(int)) from <csignal> to handle the floating point exception SIGFPE. I'd like to be able to print some useful diagnostics besides just a message saying "Floating point exception" or something to that effect. This means the function I pass as the handler to signal needs access to some of the data in my code. Therein lies the rub.
The function must return void and accept only 1 parameter of type int. I cannot make the handler a member function of my data storage class since then the type would be void(Foo::*)(int) due to the hidden this pointer.
I thought about using lambdas to try and make an anonymous function like this;
void handler(int nSig, Foo data)
{
// do something
}
// snip
Foo data;
signal(SIGFPE, [&](int nSig)->void{handler(nSig,data);});
however because the lambda captures the variable data from outside the compiler will not let it be cast to a pointer to void(*)(int) (which is a shame as this seems like an ideal use for lambdas).
I could simply make data a global variable which could then be seen in handler but I am loath to do this for obvious reasons.
So my question is thus; what is the best way of mimicking anonymous functions in C++?
Note: I would prefer a native C++ solution and not to have to use boost or equivalent.
This is indeed a good question. Let's figure out what is going before blaming C++ though. Just think about how lambdas are implemented.
The most simple lambda is when no data is captured. If that is the case, its underlying type becomes a simple plain function. For example, a lambda like this:
[] (int p0) {}
will be an equivalent of a simple function:
void foo(int p0)
{
}
That actually perfectly works in case you want that lambda to become a function pointer. For example:
#include <string>
#include <csignal>
#include <iostream>
int main()
{
int ret;
signal(SIGINT, [](int signal) {
std::cout << "Got signal " << signal << std::endl;
});
std::cin >> ret;
return ret;
}
So far so good. But now you want to associate some data with your signal handler (by the way, the code above is undefined behavior as you can only execute signal-safe code inside a signal handler). So you want a lambda like:
#include <string>
#include <csignal>
#include <iostream>
struct handler_context {
std::string code;
std::string desc;
};
int main()
{
int ret;
handler_context ctx({ "SIGINT", "Interrupt" });
signal(SIGINT, [&](int signal) {
std::cout << "Got signal " << signal
<< " (" << ctx.code << ": " << ctx.desc
<< ")\n" << std::flush;
});
std::cin >> ret;
return ret;
}
Let's forget for a moment about a syntactic sugar of C++ lambdas. It is no secret that you can "mimic" lambda even in C or assembler. So how would that look, actually? "Lambda" in C-style could look like this (this is still C++):
#include <string>
#include <cstdlib>
#include <iostream>
/*
* This is a context associated with our lambda function.
* Some dummy variables, for the sake of example.
*/
struct lambda_captures {
int v0;
int v1;
};
static int lambda_func(int p0, void *ctx) // <-- This is our lambda "function".
{
lambda_captures *captures = (lambda_captures *)ctx;
std::cout << "Got " << p0 << " (ctx: "
<< captures->v0 << ", " << captures->v1
<< ")\n" << std::flush;
return 0;
}
// Below is an example of API function provided to the user that can
// invoke a callback supplied by the user.
static void some_api_function(int (*callback)(int p, void *data), void *data)
{
callback(12345, data);
callback(98765, data);
}
int main()
{
lambda_captures captures;
captures.v0 = 1986;
captures.v1 = 2012;
some_api_function(lambda_func, (void *)&captures);
return EXIT_SUCCESS;
}
Above is a C style, C++ tends to pass "context" as "this", which is always an implicit first argument. If our API supported passing "data" as first argument, we could apply pointer to member conversion (PMF) and write something like this:
#include <string>
#include <cstdlib>
#include <iostream>
struct some_class {
int v0;
int v1;
int func(int p0)
{
std::cout << "Got " << p0 << " (ctx: "
<< v0 << ", " << v1
<< ")\n" << std::flush;
return p0;
}
};
static void some_api_function(int (*callback)(void *data, int p), void *data)
{
callback(data, 12345);
callback(data, 98765);
}
int main()
{
typedef int (*mpf_type)(void *, int);
some_class clazz({ 1986, 2012 }); // <- Note a bit of a Java style :-)
some_api_function((mpf_type)&some_class::func, (void *)&clazz);
return EXIT_SUCCESS;
}
In the above two examples, note that "data" is always passed around. This is very important. If the API that is supposed to invoke your callback does not accept a "void *" pointer that is passed back to your callback somehow, there is no way you can associate any context with the callback. The only exception is global data. For example, this API is bad:
#include <string>
#include <cstdlib>
#include <iostream>
struct lambda_captures {
int v0;
int v1;
};
static int lambda_func(int p0)
{
/*
// WHERE DO WE GET OUR "lambda_captures" OBJECT FROM????
lambda_captures *captures = (lambda_captures *)ctx;
std::cout << "Got " << p0 << " (ctx: "
<< captures->v0 << ", " << captures->v1
<< ")\n" << std::flush;
*/
return 0;
}
// Below is an example of API function provided to the user that can
// invoke a callback supplied by the user.
static void some_api_function(int (*callback)(int p))
{
callback(12345);
callback(98765);
}
int main()
{
lambda_captures captures;
captures.v0 = 1986;
captures.v1 = 2012;
some_api_function(lambda_func /* How do we pass a context??? */);
return EXIT_SUCCESS;
}
That being said, an old signal API is exactly like that. The only way to work around the problem is to actually put your "context" into a global scope. Then signal handler function can access it because the address is well known, for example:
#include <string>
#include <cstdlib>
#include <iostream>
struct lambda_captures {
int v0;
int v1;
};
lambda_captures captures({ 1986, 2012 }); // Whoa-la!!!
static int lambda_func(int p0)
{
std::cout << "Got " << p0 << " (ctx: "
<< captures.v0 << ", " << captures.v1
<< ")\n" << std::flush;
return 0;
}
// Below is an example of API function provided to the user that can
// invoke a callback supplied by the user.
static void some_api_function(int (*callback)(int p))
{
callback(12345);
callback(98765);
}
int main()
{
some_api_function(lambda_func);
return EXIT_SUCCESS;
}
This is what people have to deal with. Not only in case with signals API. This applies to other things as well. For example, interrupt handler processing. But that low-level programming where you have to deal with hardware. Of course, providing this sort of API in the user-space was not the best idea. And I will mention it again - there is only a small set of things you can do in a signal handler. You can only call async-signal-safe functions.
Of course, old API is not going away anytime soon because it is actually a POSIX standard. However, developers recognize the problem and there are better ways to handle signals. In Linux, for example, you can use eventfd to install a signal handler, associate it with arbitrary context and do whatever you want in the callback function.
At any rate, let's get back to the lambda you were playing with. The problem is not with C++, but with signals API that leaves no way for you to pass a context except using a global variable. That being said, it works with lambdas too:
#include <string>
#include <cstdlib>
#include <csignal>
#include <iostream>
struct some_data {
std::string code;
std::string desc;
};
static some_data data({ "SIGING", "Interrupt" });
int main()
{
signal(SIGINT, [](int signal) {
std::cout << "Got " << signal << " (" << data.code << ", "
<< data.desc << ")\n" << std::flush;
});
return EXIT_SUCCESS;
}
Therefore, there is no shame in what C++ is doing here as it does a right thing.
There is no such thing as an anonymous function in C (C++ is irrelevant here, as the function must abide by the C calling convention).
The only thing you can do is shiver access globals from the handler, probably global variables (and not constants which would be fine).
I advise making those globals thread local to avoid multithreading issues, but it is still bad in the sense that global variables make for more brittle applications.
How to ?
Note: as Luc Danton patiently explained to me, a signal may interrupt any non-atomic activity, and thus reading from a global is safe only if it is a lock-free atomic (or a few other things). Unfortunately std::function may not be so, depending on your implementation, I will still leave this code to explain how it could be done providing that std::function accesses are atomic.
It is possible to create a trampoline that will call stateful stuff, isolating thread and allowing re-entrant calls.
typedef std::function<void(int)> SignalHandlerType;
extern thread_local ignalHandlerType SignalHandler;
And we create the following accessor (passed to signal):
void handle_signal(int const i) {
if (SignalHandler) { SignalHandler(i); }
}
as well as the following RAII setter:
class SignalSetter: boost::noncopyable {
public:
SignalSetter(int signal, SignalHandlerType&& sh):
signal(signal), chandler(0), handler(sh)
{
chandler = std::signal(signal, &handle_signal<T>);
swap(SignalHandler, handler);
}
~SignalSetter() {
std::signal(signal, chandler);
swap(SignalHandler, handler);
}
private:
typedef void(*CHandlerType)(int);
int signal;
CHandlerType chandler;
SignalHandlerType handler;
};
Note: both the global variable and the handle_signal could be private to the SignalSetter class... but since std::signal is not...
Expected usage:
int main(int argc, char* argv[]) {
SignalSetter setter(SIGFPE, [argc, argv]() {
std::cout << argc << ": " << argc << std::endl;
});
// do what you want.
}
You cannot easily create a new static function in runtime, some JIT compilers libs are able to do this.
If you need only a reasonable number of pointers, you can create some pool of static functions by specializing a template.
So easiest way is to wrap C++ Functors by a static function. The problem here is that there is no something like user data parameter. There is only one parameter, that is a number of signal. Since there are only 64 signals, you can create a static array of std::function< void(int) > and call each depending on signal number. Some simple example:
typedef std::function< void(int) > SignalFunc;
static std::array< SignalFunc, 64 > signalsFunc;
static void cHandler(int nSig)
{
signalsFunc.at(nSig)(nSig);
}
SignalFunc RegisterSystemSignal( int sig, SignalFunc func )
{
if( signal( sig, func ? &cHandler : (sighandler_t)SIG_DFL ) != SIG_ERR )
{
func.swap( signalsFunc.at( sig ) );
return func;
}
throw some_error();
}
So now you can do that:
RegisterSystemSignal(SIGFPE, [&](int nSig)->void{handler(nSig,data);});
There is also a sigaction witch have more features.
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.