简体   繁体   中英

Qt creator : how to display function name as a string in qDebug

In the header file:

#define PRINTTCNAME(tcName)\
        qDebug() << Q_FUNC_INFO;   // error
#define RUNTC( tc)\
        PRINTTCNAME(tc);\
        res = tc();\
         if(res == false){ \
          TC_clean(); \      
        }

in the main.cpp :

int TC1_Send();
int TC2_Receive();

int main(int argc, char *argv[]){
    RUNTC(TC1_Send);
    RUNTC(TC2_Receive);
}

Problem: if I use above code, it will print the function name of int main(int, char**) which is not what I want. I want to print the name of the test case, eg TC1_Send , TC2_Receive ..

How do I proceed this ?

I think the main confusion of yours is that you think this should be a function what you are doing.

It is not. The macro is going through the preprocessor step when its content is put where the "invokation" is happening.

In that context after the preprocessor execution, this function around the code will be the main, so this is an expected behavior.

In this particular case, just use the following:

#define PRINTTCNAME(tcName)\
    qDebug() << #tcName"()";   // no error

The output will be:

TC1_Send()
TC2_Receive()

Use __FUNCTION__ instead of `Q_FUNC_INFO, it works well for me.

Correct use :

#define NAME __FUNCTION__

void test()
{
    qDebug() << NAME;
}


int main()
{
    qDebug() << NAME;
    test();
    return 0;
}

The output will be :

main

test

证明

Your code should be :

In the header file:

#include <QDebug>

#define PRINTTCNAME(tcName) qDebug() << Q_FUNC_INFO;
void RUNTC(int tc)
{
        PRINTTCNAME(tc);
        res = tc();
        if(res == false)
            TC_clean();  
}

main.cpp

int TC1_Send;
int TC2_Receive;

int main(int argc, char *argv[]){
    RUNTC(TC1_Send);
    RUNTC(TC2_Receive);
}

I use: -

  __func__ 

with this at the top of most functions: -

Log(QString("<< %1::%2 >>").arg(metaObject()->className()).arg(__func__));

Where the Log function calls qDebug, but could equally output to other locations, such as file, or system logs.

The metaObject()->className() returns the name of the class, so you'd use it if you're using a class function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM