代码之家  ›  专栏  ›  技术社区  ›  Sergei G

C printf跨平台格式,无警告[重复]

  •  -2
  • Sergei G  · 技术社区  · 7 年前

    警告:格式%lu要求参数类型为long unsigned int,但参数5的类型为size\t{aka unsigned int}

    不用说,我不想禁用警告。

    warning: format ‘%lu’ expects argument of type ‘long unsigned int’, 
    but argument 5 has type ‘uint64_t {aka long long unsigned int}’  
    
    uint64_t Created;       // 8 bytes
    time_t now = time(NULL);
    "Current time: %li sec, %lu nanosecs", now, msg.Created
    

    size\u t可能是最高的违规者:

    warning: format ‘%lu’ expects argument of type ‘long unsigned int’, 
    but argument 4 has type ‘unsigned int’
    tr_debug("pbJobs size: %lu", sizeof(pbJobs));
    

    tr_调试相当于Mbed操作系统平台的printf。是的,我在Mbed操作系统和Linux上编译。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Steve Summit    7 年前

    对于 size_t %zu .

    如果你不能使用 z 修饰符(遗憾的是,一些较旧的库不支持),在打印时转换为足够宽的已知类型,然后使用适合该类型的宽度说明符:

    size_t sz = sizeof(whatever);
    ...
    printf("%lu", (unsigned long)sz);
    

    这很有效 只要 大小\u t long 大小\u t 可以容纳但 %lu 无法打印。这是否是你的问题,如果是,该怎么办,这取决于你。(如果您的库支持,理想的解决方案是返回到 %祖 unsigned long long %llu .)

        2
  •  0
  •   Baum mit Augen    7 年前

    #include <cstdint>
    
    int8_t a = 15; //usually an alias for char
    uint16_t b = 4980; //usually an alias for unsigned short
    uint32_t c = 1234567890; //usually an alias for unsigned int or unsigned long
    int64_t d = 908070605040302010ll; //usually an alias for long long
    

    大小整数的技巧是,例如, long 在一个平台上是32位,但在另一个平台上是64位 不可携带。但是 int64_t 总是 是64位,否则它在给定的平台上根本不存在。

    size_t 将始终是64位,但无法保证这一点。所以你应该使用 uint64_t 相反,它保证了无论最终使用何种底层数据类型,它都将是64位(无符号,这是与 大小\u t ).