Errore durante la registrazione delle macro del preprocessore C ++ __LINE__, __FUNCTION__

StackOverflow https://stackoverflow.com/questions/622129

  •  05-07-2019
  •  | 
  •  

Domanda

Sto cercando di incorporare un semplice errore nella registrazione della mia app esistente, al momento segnala errori usando solo cout quindi speravo di mantenere un'interfaccia simile usando l'operatore <<. Tuttavia, desidero che registri la riga e funzioni l'errore si è verificato, ma non voglio digitare __LINE__, __FUNCTION__ ogni volta che devo accedere. Qualcuno sa un trucco che posso usare per consentire alla macro __LINE__ di essere utilizzata all'interno di un'altra funzione, segnalando invece la linea chiamante? Spero che abbia un senso.

class myLogClass {
    uint8_t level;                  
public:                 
    bool operator<<( const char * input );          
};

bool myLogClass::operator<<( const char * input ) {
    logItInSQL( input );
    return true;
}

Invece di questo ogni volta

myLogClass << "Line No: " << __LINE__
    << " Function: " << __FUNCTION__
    << " Error: " << "This is my error to be logged";

Vorrei solo essere in grado di fare:

myLogClass << "This is my error to be logged";

bool myLogClass::operator<<( const char * input ) {
    logItInSQL( " Line No: __LINE__" );
    logItInSQL( " Function: __FUNCTION__" );
    logItInSQL( " Error: " + input );
    return true;
}
È stato utile?

Soluzione

myLogClass << "Line No: " << __LINE__ ...

Con il tuo operator << concatenamento non funzionerà poiché restituisce bool.

bool myLogClass::operator << (const char * input)

È consuetudine definire l'inserimento dello stream come segue:

std::ostream& myLogClass::operator << (std::ostream& o, const char * input) {
    // do something
    return o;
}

Fai questo:

#define log(o, s) o << "Line No: " << __LINE__ << \
                   " Function: " << __FUNCTION__ << \
                   " Error: " << s // note I leave ; out

Inoltre, puoi avvolgere la macro in un do-while ciclo:

#define log(o, s) do { o << "Line No: " << __LINE__ << \
                   " Function: " << __FUNCTION__ << \
                   " Error: " << s; \ 
                  } while(0) // here, I leave ; out

Quindi puoi tranquillamente scrivere:

 myLogClass myLogger; // do this

 // use it
log(myLogger, "This is my error to be logged"); // note the ;

Altri suggerimenti

In ANSI C (che dovrebbe funzionare anche in C ++ suppongo), puoi farlo usando le funzioni variadiche e le macro del preprocessore. Vedi l'esempio seguente:

#include <stdio.h>
#include <stdarg.h>

#define MAXMSIZE 256
#define MyDebug(...) MyInternalDebug(__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__)

void MyInternalDebug( char *file, char *function, const int line, const char *format, ... )
{
    char message[MAXMSIZE];
    // Variable argument list (VA)
    va_list ap;
    // Initialize VA
    // args : Name of the last named parameter in the function definition.
    // The arguments extracted by subsequent calls to va_arg are those after 'args'.
    va_start(ap, format);

    // Composes a string with the same text that would be printed if 'format' was used on printf,
    // but using the elements in the variable argument list identified by 'ap' instead of
    // additional function arguments and storing the resulting content as a C string in the buffer pointed by 'message'.
    // * The state of arg is likely to be altered by the call.
    vsprintf(message, format, ap);
    // Custom print function
    printf("%s\t%s\t%d\t%s\n",file, function, line, message);

    // Finzalize use of VA
    va_end(ap);
}

int main ()
{  
    MyInternalDebug(__FILE__, __FUNCTION__, __LINE__, "An error occured with message = '%s'", "Stack Overflow");
    MyDebug("Another error occured with code = %d", 666);

    return 0;
}

No, questo è il motivo per cui la registrazione viene eseguita con le macro. __LINE__ deve essere espanso dal preprocessore sulla riga in questione, non in una funzione di registrazione comune.

Come menzionato da Adam Mitz, è necessario utilizzare __LINE__ nel luogo di chiamata.
Ti consiglio di aggiungere un parametro extra come & Quot; additionalInfo & Quot; e creare una macro che genererà questo " additionalInfo " usando __LINE__ e __FUNCTION__.

Non è stato possibile ottenere il codice nella prima risposta da compilare. Uso questa semplice macro che svolge bene il compito:

#define qlog(s) std::cerr << __FUNCTION__ << "::" << __LINE__ << "\t" << s << endl

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top