How to find the name of the current function at runtime? - c++

After years of using the big ugly MFC ASSERT macro, I have finally decided to ditch it and create the ultimate ASSERT macro.
I am fine with getting the file and line number, and even the expression that failed. I can display a messagebox with these in, and Abort/Retry/Cancel buttons.
And when I press Retry the VS debugger jumps to the line containing the ASSERT call (as opposed to the disassembly somewhere like some other ASSERT functions). So it's all pretty much working.
But what would be really cool would be to display the name of the function that failed.
Then I can decide whether to debug it without trying to guess what function it's in from the filename.
e.g. if I have the following function:
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
ASSERT(lpCreateStruct->cx > 0);
...
}
Then when the ASSERT fires, the messagebox would show something like:
Function = CMainFrame::OnCreate
So, what's the simplest way of finding out the current function name, at runtime?
It should not use MFC or the .NET framework, even though I do use both of these.
It should be as portable as possible.

Your macro can contain the __FUNCTION__ macro.
Make no mistake, the function name will be inserted into the expanded code at compile time, but it will be the correct function name for each call to your macro. So it "seems like" it happens in run-time ;)
e.g.
#define THROW_IF(val) if (val) throw "error in " __FUNCTION__
int foo()
{
int a = 0;
THROW_IF(a > 0); // will throw "error in foo()"
}

The C++ preprocessor macro __FUNCTION__ gives the name of the function.
Note that if you use this, it's not really getting the filename, line number, or function name at runtime. Macros are expanded by the preprocessor, and compiled in.
Example program:
#include <iostream>
void function1()
{
std::cout << "my function name is: " << __FUNCTION__ << "\n";
}
int main()
{
std::cout << "my function name is: " << __FUNCTION__ << "\n";
function1();
return 0;
}
output:
my function name is: main
my function name is: function1

There's no standard solution. However, BOOST_CURRENT_FUNCTION is portable for all practical purposes. The header does not not depend on any of the other Boost headers, so can be used standalone if the overhead of the whole library is unacceptable.

__FUNCTION__ or __FUNC__ or __PRETTY_FUNCTION__
http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx
http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html

In GCC you can use the __PRETTY_FUNCTION__ macro.
Microsoft also have an equivalent __func__ macro although I don't have that available to try.
e.g. to use __PRETTY_FUNCTION__ putting something like this at the beginning of your functions and you'll get a complete trace
void foo(char* bar){
cout << __PRETTY_FUNCTION__ << std::endl
}
which will output
void foo(char* bar)
You also have the __FILE__ and __LINE__ macros available under all standard c/c++ compilers if you want to output even more information.
In practice I have a special debugging class which I use instead of cout. By defining appropriate environment variables I can get a full program trace. You could do something similar. These macros are incredibly handy and it's really great to be able to turn on selective debugging like this in the field.
EDIT: apparently __func__ is part of the standard? didn't know that. Unfortunately, it only gives the function name and not the parameters as well. I do like gcc's __PRETTY_FUNC__ but it's not portable to other compilers.
GCC also supports __FUNCTION__.

You can use the __FUNCTION__ macro which at compile time will be expanded to the name of the function.
Here's an example of how to use it in an assert macro.
#define ASSERT(cond) \
do { if (!(cond)) \
MessageBoxFunction("Failed: %s in Function %s", #cond, __FUNCTION__);\
} while(0)
void MessageBoxFunction(const char* const msg, ...)
{
char szAssertMsg[2048];
// format args
va_list vargs;
va_start(vargs, msg);
vsprintf(szAssertMsg, msg, vargs);
va_end(vargs);
::MessageBoxA(NULL, szAssertMsg, "Failed Assertion", MB_ICONERROR | MB_OK);
}

C++20 std::source_location::function_name
No macros are needed now that we have proper standardization:
main.cpp
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location = std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int f(int i) {
log("Hello world!"); // Line 16
return i + 1;
}
int f(double i) {
log("Hello world!"); // Line 21
return i + 1.0;
}
int main() {
f(1);
f(1.0);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++20 -Wall -Wextra -pedantic -o source_location.out source_location.cpp
./source_location.out
Output:
info:source_location.cpp:16:int f(int) Hello world!
info:source_location.cpp:21:int f(double) Hello world!
so note how the call preserves caller information, so we see the desired main call location instead of log.
I have covered the relevant standards in a bit more detail at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?
Tested on Ubuntu 22.04, GCC 11.3.

you can easily use func.
it will take back you current function name at runtime which raised the exception.
usage:
cout << __func__ << ": " << e.what();

Related

Is there a way to ensure lazy evaluation of BOOST_TESTs message?

Is it possible to ensure that the message macro parameter of BOOST_TEST is only evaluated, if the check actually fails. Lazy evaluation seems to happen for human readable output format, but not for JUnit output format. Can I somehow make lazy evaluation work reliably for all output types?
MCVE
#define BOOST_TEST_MODULE my_module
#include <boost/test/included/unit_test.hpp>
#include <string>
struct S
{
std::string m_value;
};
S* f(void)
{
return nullptr;
}
BOOST_AUTO_TEST_CASE(foo_test)
{
S* result = f();
BOOST_TEST(result == nullptr, "f() should return nullptr but returned a object with m_value = " << result->m_value);
}
This code works fine if I use human readable output format (--log_format=HRF command line option for executable). Using JUnit output (--log_format=JUNIT command line option) results in a access error, since the program attempts to get the size of a string at address 0.
This is a bit unexpected, since I'd assume the BOOST_TEST macro would work similar to this
// not the real macro, but one that works in a way I'd expect it to work
#define BOOST_TEST(condition, message) if (!(condition)) { \
some_output_stream << "The following test failed: " << #condition << std::endl \
<< "Message: " << message; \
}
Tested configurations:
boost 1.75.0
Visual Studio 2017/2019 or g++ 8.x (Win 10 / Ubuntu 18)
64 bit

Create a flag for a Qt project or use QLoggingCategory

This is my first question on this website, I hope I'll do it just fine.
I'm doing a Qt Project at work using a lot of signals and slots and I would like to create a flag/macro/variable to activate/deactivate the use of std::cout to trace which signal is emitted and which slot is activated.
This is for debugging purpose, to know how the different components of the application exchange and avoid loops in signals/slots.
More specifically, I would have a flag/variable in my .pro :
QT_SIGNALS_SLOTS_LOG = true
and in my source code :
if(QT_SIGNALS_SLOTS_LOG)
std::cout << "MyClass::slotMySlot activated" << std::endl;
Questions :
1. Can I do something like that (using a variable of the .pro in the
code) ?
2. Is there a better way of doing that ?
UPDATE 1
Burich, this works just fine, thanks
Now I will try to code a Qt macro which I put in my slots and wich does all the work
Example :
Q_SIGNALS_SLOTS_LOG();
which gets the names of the Class and the Slot and do the
ifdef QT_SIGNALS_SLOTS_LOG
std::cout << "MyClass::slotMySlot activated" << std::endl;
endif
Is there a way of doing that ?
UPDATE 2
I used QLoggingCategory Class with this tutorial
I have a Class in my Utils folder with this code
#ifndef SIGNALSLOTDEBUG_H
#define SIGNALSLOTDEBUG_H
#include<QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(logSignal)
Q_DECLARE_LOGGING_CATEGORY(logSlot)
inline static void debugSlotF( char const * caller_name )
{
qCDebug(logSlot) << __TIME__ << caller_name << "activated";
}
inline static void debugSlot(){
}
#define debugSlot() debugSlotF(__PRETTY_FUNCTION__)
#endif // SIGNALSLOTDEBUG_H
In my code I just call
void HorizontalPatternListScene::slotSelectionChanged(int i)
{
debugSlot();
....
I get this output :
log.slot: 12:06:54 void HorizontalPatternListScene::slotSelectionChanged(int) activated
And I can disable the stream by doing
QLoggingCategory::setFilterRules(
"log.slot=true\n"
"log.signal=false");
in my main.cpp
Set variable in pro:
DEFINES += QT_SIGNALS_SLOTS_LOG
Test it in code:
#ifdef QT_SIGNALS_SLOTS_LOG
std::cout << "MyClass::slotMySlot activated" << std::endl;
#endif
If you're willing to use C++11 features for this, you can so the following:
#ifdef DEBUGMYCODE
template<typename... ArgTypes>
inline void print(ArgTypes... args)
{
// trick to expand variadic argument pack without recursion
using expand_variadic_pack = int[];
// first zero is to prevent empty braced-init-list
// void() is to prevent overloaded operator, messing things up
// trick is to use the side effect of list-initializer to call a function on every argument, in order.
// (void) is to suppress "statement has no effect" warnings
#ifdef _WIN32
std::stringstream stream;
(void)expand_variadic_pack{0, ((stream << args), void(), 0)... };
std::wstring stuff = convert_to_utf16(stream.str());
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), stuff.c_str(), stuff.size(), nullptr, nullptr);
#else
(void)expand_variadic_pack{0, ((std::cout << args), void(), 0)... };
#endif
}
#else
#define debug_print(...)
#endif
I use this in my code as a general "print" function and add a debug enum on top to handle debug types being output at runtime.
It handles UTF-8 strings on Windows as a bonus, and handles anything that can be dumped to std::cout. You can also change what stream it outputs to, or really whatever the body of the function does.
If the macro DEBUGMYCODE is not defined, all calls to debug_print are fully removed by the preprocessor.
PS: if it's Qt you're coding, you should really use qDebug() which handles this for you in an entirely different manner.

Compiler optimization merge identical functions implementation meant to be stubs to be detoured during runtime

I have a C++ test project with a bunch of stub functions that have the same implementation. Those stubs are meant to be 'replaced' during runtime using Windows Detours. The issue is that, in release mode, the compiler make all of those stubs to point to the same implementation. To illustrate this, consider this code:
#include <iostream>
using namespace std;
void A() { cout << "stub" << endl; }
void B() { cout << "stub" << endl; }
void main()
{
cout << &A << ", " << &B << endl;
}
In debug mode, the pointer values will be different. In release mode, they are the same.
I tried the pragma optimize directive (I am using the Microsoft compiler) but it didn't fix the issue. As a result, my Windows Detours hook intercept all the calls to the identical stubs.
How can I fix this?
Thanks.
Try using preprocessor macros to make your stub functions unique so the optimizer won't merge them into one.
__FILE__, __LINE__, and __FUNCTION__ usage in C++
Something like this:
void A() { cout << __FUNCTION__ << endl; }
void B() { cout << __FUNCTION__ << endl; }

How do I imitate the Microsoft version of __FUNCTION__ using gcc?

When I use the __FUNCTION__ macro/variable to print out debugging information, there seems to be a difference in what it outputs when using the Microsoft C++ compiler and gcc. For example, using the following trivial code:
class Foo
{
public:
void Bar(int a, int b, int c)
{
printf ("__FUNCTION__ = %s\n", __FUNCTION__);
}
};
int main (void)
{
Foo MyFoo;
MyFoo.Bar();
return 0;
}
Using the Microsoft Visual C++ compiler, I get
__FUNCTION__ = Foo::Bar
whereas when compiling using gcc (in this case on the Mac), I get
__FUNCTION__ = Bar
The second example is not ideal because I quite often have several classes with, say, Init() and Uninit() methods and in a debug output trace its virtually impossible to tell which one of these has been called as the class name will be missing. Now, I know you can use the __PRETTY_FUNCTION__ in place of __FUNCTION__ to get something like
__PRETTY_FUNCTION__ = void Foo::Bar(int, int, int)
Which is fine, but its a bit too verbose for what I need and gets a bit long for functions with a lot of parameters.
So my question is (at last), is there any way to get the output to look like simply Foo::Bar using gcc, as in the example above?
If you are using it for tracing, you can always use typeid(T).name() and just conditionally compile per platform. Certainly not as convenient as the macro, but it could work.
Vaguely similar to __CLASS__ macro in C++
The function-name sanctioned by the standard is defined as follows:
static const char __func__[] = "function-name ";
Example:
#include <iostream>
namespace meh {
void foobar() { std::cout << __func__ << std::endl; }
};
struct Frob {
void foobar() { std::cout << __func__ << std::endl; }
static void barfoo() { std::cout << __func__ << std::endl; }
};
int main () {
std::cout << __func__ << std::endl;
meh::foobar();
Frob().foobar();
Frob::barfoo();
}
However, output with g++:
main
foobar
foobar
barfoo
However, that is valid C++ behaviour:
ยง 8.4.1, 8: The function-local predefined variable __func__ is defined as if a definition of the form static const char __func__[] = "function-name ";
had been provided, where function-name is an implementation-defined string. It is unspecified whether such a variable has an address distinct from that of any other object in the program
I.e., you may not trust in its value. If you want to use non-portable extensions, have a look at a similar question: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__? .

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

I want to implement a function tracer, which would trace how much time a function is taking to execute. I have following class for the same:-
class FuncTracer
{
public:
FuncTracer(LPCTSTR strFuncName_in)
{
m_strFuncName[0] = _T('\0');
if( strFuncName_in ||
_T('\0') != strFuncName_in[0])
{
_tcscpy(m_strFuncName,strFuncName_in);
TCHAR strLog[MAX_PATH];
_stprintf(strLog,_T("Entering Func:- <%s>"),m_strFuncName);
LOG(strLog)
m_dwEnterTime = GetTickCount();
}
}
~FuncTracer()
{
TCHAR strLog[MAX_PATH];
_stprintf(strLog,_T("Leaving Func:- <%s>, Time inside the func <%d> ms"),m_strFuncName, GetTickCount()-m_dwEnterTime);
LOG(strLog)
}
private:
TCHAR m_strFuncName[MAX_PATH];
DWORD m_dwEnterTime;
};
void TestClass::TestFunction()
{
// I want to avoid writing the function name maually..
// Is there any macro (__LINE__)or some other way to
// get the function name inside a function ??
FuncTracer(_T("TestClass::TestFunction"));
/*
* Rest of the function code.
*/
}
I want to know if there is any way to get the name of the function from inside of a function? Basically I want the users of my class to simply create an object the same. They may not pass the function name.
C99 has __func__, but for C++ this will be compiler specific. On the plus side, some of the compiler-specific versions provide additional type information, which is particularly nice when you're tracing inside a templatized function/class.
MSVC: __FUNCTION__, __FUNCDNAME__, __FUNCSIG__
GCC: __func__, __FUNCTION__, __PRETTY_FUNCTION__
Boost library has defined macro BOOST_CURRENT_FUNCTION for most C++ compilers in header boost/current_function.hpp. If the compiler is too old to support this, the result will be "(unknown)".
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__ );
C++20 std::source_location::function_name
main.cpp
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location = std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int f(int i) {
log("Hello world!"); // Line 16
return i + 1;
}
int f(double i) {
log("Hello world!"); // Line 21
return i + 1.0;
}
int main() {
f(1);
f(1.0);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++20 -Wall -Wextra -pedantic -o source_location.out source_location.cpp
./source_location.out
Output:
info:source_location.cpp:16:int f(int) Hello world!
info:source_location.cpp:21:int f(double) Hello world!
so note how the call preserves caller information, so we see the desired main call location instead of log.
I have covered the relevant standards in a bit more detail at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?
Tested on Ubuntu 22.04, GCC 11.3.
I was going to say I didn't know of any such thing but then I saw the other answers...
It might interest you to know that an execution profiler (like gprof) does exactly what you're asking about - it tracks the amount of time spent executing each function. A profiler basically works by recording the instruction pointer (IP), the address of the currently executing instruction, every 10ms or so. After the program is done running, you invoke a postprocessor that examines the list of IPs and the program, and converts those addresses into function names. So I'd suggest just using the instruction pointer, rather than the function name, both because it's easier to code and because it's more efficient to work with a single number than with a string.