Neko
Neko

Reputation: 45

Is it possible to dynamically create equivalent of limits.h macros during compilation?

Main reason for this is attempt to write perfectly portable C library. After a few weeks i ended up with constants, which are unfortunately not very flexible (using constants for defining another constants isn't possible). Thx for any advice or critic.

Upvotes: 0

Views: 158

Answers (2)

Kaslai
Kaslai

Reputation: 2505

What you ask of is impossible. As stated before me, any standards compliant implementation of C will have limits.h correctly defined. If it's incorrect for whatever reason, blame the vendor of the compiler. Any "dynamic" discovery of the true limits wouldn't be possible at compile time, especially if you're cross compiling for an embedded system, and thus the target architecture might have smaller integers than the compiling system.

To dynamically discover the limits, you would have to do it at run-time by bit shifting, multiplying, or adding until an overflow is encountered, but then you have a variable in memory rather than a constant, which would be significantly slower. (This wouldn't be reliable anyways since different architectures use different bit-level representations, and arithmetic sometimes gets a bit funky around the limits especially with signed and abstract number representations such as floats)

Just use standard types and limits as found in stdint.h and limits.h, or try to avoid pushing the limits all together.

Upvotes: 1

smbear
smbear

Reputation: 1041

First thing that comes to my mind: have you considered using stdint.h? Thanks to that your library will be portable across C99-compliant compilers.

Upvotes: 1

Related Questions