Problem description
stay C/C++ In development , Use printf Print 64 Bit variables are commonly used , Usually in 32 Bit system %lld Output 64 Bit variables , And in the 64 In the bit system %ld;
If in 32 Bit system %ld Output 64 Bit variable , It is likely that the printed value is abnormal , And in the 64 In the bit system %lld, Compilation errors usually occur , Similar to :
format '%lld' expects type 'long long int', but argument 4 has type 'int64_t'[ -Werror=format=]
If you migrate code across platforms , This is usually the case .
Solution
In order to solve the problem of cross platform migration ,% PRId64 The way of writing solves the problem of cross platform , Mainly to support 32 Bit and 64 Bit operating system .PRId64 Express 64 An integer , stay 32 Bit system long long int, stay 64 Bit system long int.
Writing format :
uint64_t value = 1560;
printf("value = %" PRId64 "\n", value);
The effect is as follows :
uint64_t value = 1560;
printf("value = %" "%ld" "\n", value); // 64bit OS
printf("value = %" "%lld" "\n", value); // 32bit OS
perhaps
uint64_t value = 1560;
printf("value = %ld\n", value); // 64bit OS
printf("value = %lld\n", value); // 32bit OS