The existing answers simply show how to achieve the effect of โcompile-time statementsโ depending on the type size. This may satisfy the needs of the OP in this particular case, but there are other cases where you really need a conditional preprocessor based on the type size. Here's how to do it:
Write yourself a small C program, for example:
#include <stdio.h> /* 'int' is just an example, it could be any other type */ int main(void) { printf("%zd", sizeof(int); }
Compile this. Write a script in your favorite scripting language that runs the above C program and captures its output. Use this output to create a C header file. For example, if you used Ruby, it might look like this:
sizeof_int = `./sizeof_int` File.open('include/sizes.h','w') { |f| f.write(<<HEADER) } /* COMPUTER-GENERATED, DO NOT EDIT BY HAND! */ #define SIZEOF_INT #{sizeof_int} /* others can go here... */ HEADER
Then add the rule to your Makefile or other build script that will make it run the above script to build sizes.h .
Include sizes.h wherever you need to use preprocessor conventions based on sizes.
Done!
(Have you ever typed ./configure && make to create a program? What does configure scripts do basically the same as above ...)
Alex D Aug 31 '15 at 8:53 2015-08-31 08:53
source share