有一个调试类,用于根据级别打印出调试语句。级别越高,您收到的消息越详细。当我尝试打印uint64_t时会发生问题。在使用printf样式的不同平台上,它可能是%li或%lli。我希望它变得便携。但是,基于this,我可以包含PRId64,并且可以进行相应调整。问题是因为我的消息是自定义的,它采用了const char *。我无法处理诸如"Calling based on pts %"PRId64, mv.pts之类的消息,因为它期待的是char *,而其中没有一个。还有什么其他方法可以解决这个问题?

内部代码

#include "debug.h"
#include <inttypes.h>

#define P_DBG(level, format, ...) DBGPRINT(level, ("%-5d%s::%s() - " format "\n", __LINE__, str().c_str    (), __FUNCTION__, __VA_ARGS__))
#define P_ALL(format, ...) P_DBG(P_ALWAYS, format, __VA_ARGS__)
class Something
{
    Something::Print(uint64_t a) {
        P_ALL("Calling based on %"PRId64 "\n", a)
}


在debug.h内部

class vdebugPrint {
class vdebugPrint(int ID, int level) : v_id(ID), v_level(level) {}
int Print(const char* formatString, ...) __attribute__((__format(printf,2,3)));
}
...
#define VPRINT3(level, msg)    VdebugPrint(ID, level).Print msg
#define PRINT(level, msg)     VPRINT##level(level,msg)
#define DBGPRINT(level, msg)     PRINT(level,msg)
...


内部debug.cpp

...
VdebugPrint::Print(const char* format, ...)
{
    va_list argumentList;
    va_start(argumentList, formatString);
    vprintf(formatString, argumentList);
    va_end(argumentList);
}


确切的错误消息是

error: expected ‘)’ before ‘PRId64’
     AV_TRACE("Calling based on %"PRId64"\n", mv.pts);
                                  ^
/.../debug.h:140:94: note: in definition of macro ‘VPRINT3’
 #define VPRINT3(level, msg)      VdebugPrint(ID, level).DebugPrint msg

/.../debug.h:146:45: note: in expansion of macro ‘DBGPRINT’
 #define DBGPRINT(level, msg)            PRINT(level, msg)
                                         ^
/.../file.h:54:41: note: in expansion of macro ‘DBGPRINT’
#define P_PBD(level, format, args...)  DBGPRINT(level, ("%-5d%s::%s() - " format "\n", __LINE__, str().c_str(), __FUNCTION__, ##args))


编辑:

我尝试过奥拉夫的建议无济于事。这是我所做的。除主代码外,其他所有内容均相同。

...
class Something
{
    Something::Print(uint64_t a) {
        const char* message = "Calling based on %";
        size_t mlen = strlen(message);
        char buf[mlen + strlen(PRId64) + 1];
        strcpy(buf, message);
        strcpy(buf + mlen, PRId64);

        P_ALL(buf, a);
    }
}


我得到的错误是

error: ‘PRId64’ was not declared in this scope
     char buf[mlen + strlen(PRId64) + 1];
                            ^


EDIT2:所以我解决了找不到PRId64的问题。在包含整型之前,我必须从here定义__STDC_FORMAT_MACROS。现在可以解决问题并编译!

最佳答案

inttypes.h中定义的宏是带有正确的printf类型说明符的字符串文字。因此,您必须将此附加到格式字符串。正常用法是使用字符串文字串联。

如果格式字符串是可变的,则必须在字符串后附加说明符:

char buf[strlen[format] + strlen[PRId64] + 1];
strcpy(buff, format);
strcat(buff, PRId64);


请注意,可以使用strcpy对这两者进行优化:

size_t flen = strlen(format);
char buf[flen + strlen[PRId64] + 1];
strcpy(buff, format);
strcpy(buff + flen, PRId64);


注意:格式字符串必须为NUL终止!

更新:

最初的答案是C,因为它是语言标签之一,并且代码看起来更像C,而不是C ++。但是,根据注释,如果您在#define __STDC_FORMAT_MACROS之前#include <inttypes.h>,也可以将其用于C ++ 11(检查编译器的支持)。 (请注意,include可能会出现在其他标题中,因此您应该尽早在文件中定义宏。)

09-04 07:33
查看更多