3

I am developing using gcc (-std=gnu99) for an embedded toolchain (Myriota), and I have problems with printf.

when I try the following code:

long long int time = TimeGet();
printf("\nSeconds since epoch: %lld\r\n", time);

it prints:

Seconds since epoch: ld

Using "%" PRId64 prints the same "ld".

Any ideas? I'd appreciate if you could point me to the right place.

Edit variable type corrected long long int time

bot1131357
  • 877
  • 8
  • 25
  • 1
    Thanks for the comment, you were right to point out that the type was incorrect. It was a long long int. I suspected this to be a bug, but I needed a sanity check. I'll contact Myriota. – bot1131357 Oct 04 '19 at 02:56

3 Answers3

6

Most likely, your C library, specifically its implementation of printf, doesn't support C99.

The type long long int and the %lld format were introduced by the 1999 ISO C standard (C99). Using gcc -std=c99 makes the compiler attempt to conform to C99, (or -std=cNN for later editions) but it can't make the runtime library do things that it doesn't implement. You have a mismatch between what the compiler supports and what the runtime library supports.

In C90, calling printf with %lld in the format string had undefined behavior.

Does %ld work for an argument of type long int? If the argument is in the range LONG_MIN to LONG_MAX, converting and using %ld might be a good workaround. If you need to print values less than LONG_MIN or greater than LONG_MAX, implementing a long long int to string conversion isn't horribly difficult. (And in some implementations, long int and long long int are both 64 bits, so just converting to long int and using %ld is sufficient.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
1

The Myriota SDK uses newlib-nano which does not support int64_t. I'll have to implement my own function to convert to char string, or cast to uint32_t.

bot1131357
  • 877
  • 8
  • 25
0
#include <stdio.h>

void int64_to_string(int64_t num, char* str) {
    if (num < 0) {
        *str++ = '-';
        num = -num;
    }

    char buffer[20]; // Maximum 19 digits in int64_t
    int i = 0;
    do {
        buffer[i++] = num % 10 + '0';
        num /= 10;
    } while (num != 0);

    while (i > 0) {
        *str++ = buffer[--i];
    }
    *str = '\0';
}
int64_t num = 1234567890123456789;
char str[20]; // Maximum 19 digits in int64_t
int64_to_string(num, str);
printf("%s\n", str); // Output: "1234567890123456789"
Nicolas VERHELST
  • 398
  • 3
  • 13