Skip to content

Instantly share code, notes, and snippets.

@StarJade-Park
Created January 28, 2020 04:32
Show Gist options
  • Save StarJade-Park/e222a31ccd2257de14c8e9e355ca1215 to your computer and use it in GitHub Desktop.
Save StarJade-Park/e222a31ccd2257de14c8e9e355ca1215 to your computer and use it in GitHub Desktop.
How to get class name and method name in MSVC
#include <iostream>
#include <string>
using namespace std;
// * REFERENCE LINK : https://stackoverflow.com/questions/1666802/is-there-a-class-macro-in-c
static inline std::string className(const std::string& prettyFunction)
{
size_t colons = prettyFunction.find("::");
if ( colons == std::string::npos )
return "::";
size_t begin = prettyFunction.substr(0, colons).rfind(" ") + 1;
size_t end = colons - begin;
return prettyFunction.substr(begin, end);
}
static inline std::string methodName(const std::string& prettyFunction)
{
size_t colons = prettyFunction.find("::");
size_t begin = prettyFunction.substr(0, colons).rfind(" ") + 1;
size_t end = prettyFunction.rfind("(") - begin;
return prettyFunction.substr(begin, end) + "()";
}
#define __CLASS_NAME__ className(__FUNCSIG__)
#define __METHOD_NAME__ methodName(__FUNCSIG__)
class Foo
{
public:
static void static_func( )
{
std::string class_name = __CLASS_NAME__;
std::string class_func = __METHOD_NAME__;
std::cout << "- Foo static " << class_name << ", " << class_func << "\n";
}
void member_func( )
{
std::string class_name = __CLASS_NAME__;
std::string class_func = __METHOD_NAME__;
std::cout << "- Foo member " << class_name << ", " << class_func << "\n";
}
};
// * REFERENCE : MSDN predefined macros example
// Demonstrates functionality of __FUNCTION__, __FUNCDNAME__, and __FUNCSIG__ macros
void exampleFunction( )
{
printf("- Function name: %s\n", __FUNCTION__);
printf("- Decorated function name: %s\n", __FUNCDNAME__);
printf("- Function signature: %s\n", __FUNCSIG__);
}
int main()
{
exampleFunction( );
Foo::static_func( );
Foo f{};
f.member_func( );
std::cout << "= Main function signature : " << __FUNCSIG__ << "\n";
}
/*
Example output
-------------------------------------------------
- Function name: exampleFunction
- Decorated function name: ?exampleFunction@@YAXXZ
- Function signature: void __cdecl exampleFunction(void)
- Foo static Foo, Foo::static_func()
- Foo member Foo, Foo::member_func()
= Main function signature : int __cdecl main(void)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment