0

I have a file which will be bundled into two shared libraries. The compiler creates two versions of the library: one for the 32-bit type and another for the 64-bit type. Now I need to print a diagnostic log involving a variable:

size_t len;

and the print statement format specifier is as follows:

LOG("The length is %ld",len);

When the compiler creates a 64 bit version it complains:

format specifies type 'unsigned int' but the argument has type 'size_t' (aka 'unsigned long') [-Wformat]

If I change it from %ld to %lu then the 32 bit version complains:

format specifies type 'unsigned long' but the argument has type 'size_t' (aka 'unsigned int') [-Wformat]

How do I avoid the -Wformat error (of course suppressing it isn't a solution I am looking for) ? Do I have to resort to #ifdefs for checking compiler version and writing the diagnostic accordingly ?

Compiler version: Clang 3.8 (Android Platform)

Edit: Somebody duplicated it to a related question. Let me pose it with a different example since size_t appears to be common:

jlong val;
LOG("val = %ld",val):

When running 32 bit compiler pass:

warning: format specifies type 'long' but the argument has type 'jlong' (aka 'long long') [-Wformat]

So if I try to change it to %lld to suppress warning then I get: When running 64 bit pass:

warning: format specifies type 'long long' but the argument has type 'jlong' (aka 'long') [-Wformat]

How to deal with such cases ? And reiterating again:

Compiler version: Clang 3.8 (Android Platform)

Zoso
  • 3,273
  • 1
  • 16
  • 27

1 Answers1

0

If you have a compiler that supports C++17, you can do something like this.

enum class Environment { bit32, bit64 };

#ifdef __x86_32__
constexpr Environment environment = Environment::bit32;
#elif __x86_64__
constexpr Environment environment = Environment::bit64;
#endif

void print_statement() 
{      
   if constexpr (environment == Environment ::bit32) {
     // do your 32 bit thing.
   }
   else if constexpr (environment == Environment ::bit64) {
     // do your 64 bit thing.
   }
}
0xBADF00
  • 1,028
  • 12
  • 26