Search code examples
c++cmacroscompatibilityglibc

stdint.h not compatible with C++?


I tried to compile a source code package, and found version-specific issues.

When I do that on my computer, everything goes well; but when I compile it on another computer, it produces a lot of claims that INT32_MAX is not defined. Both computer runs a Debian system, and the difference is my computer uses Testing repo and has gcc 4.9, and the other computer uses Stable repo., which has slightly older gcc 4.7.

Then I have a detailed look inside /usr/include/stdint.h. By surprise, on the computer claiming the undefined macros, all int range macros are defined inside a non-C++ condition:

/**
 * I forget the exact definition,
 * but it looks like this:
 */
#ifndef __cplusplus ......
......
# define INT32_MIN XXX
# define INT32_MAX XXX
......
#endif

As a result, the package won't see these standard range macros, as it is a C++ project, and uses g++ to compile.

Why the stdint.h of gcc 4.7 is designed like this? Is that means gcc 4.7 don't want me to use those integer ranges with C++, and gcc 4.9 allows it?

And the most important: how should I work around this?


Solution

  • In C++ you're recommended to use std::numeric_limits #include <limits>:

    Usage example from cplusplus.com

    // numeric_limits example
    #include <iostream>     // std::cout
    #include <limits>       // std::numeric_limits
    
    int main () {
      std::cout << std::boolalpha;
      std::cout << "Minimum value for int: " << std::numeric_limits<int>::min() << '\n';
      std::cout << "Maximum value for int: " << std::numeric_limits<int>::max() << '\n';
      std::cout << "int is signed: " << std::numeric_limits<int>::is_signed << '\n';
      std::cout << "Non-sign bits in int: " << std::numeric_limits<int>::digits << '\n';
      std::cout << "int has infinity: " << std::numeric_limits<int>::has_infinity << '\n';
      return 0;
    }