问题
Where can I go to get information about the size of, say, unsigned int
compiling under gcc
for Mac OS X (both 32 and 64 bits)? In general I'd love to have a resource I can go to with a compiler/settings/platform/type and be able to look up how big that type will be. Does anyone know of such a thing?
Update: Thanks for all the responses. I was hoping to have something more along the lines of a static table somewhere instead of a piece of code I'd have to write and run on every machine.
回答1:
If you can't write a program to find out, you should consult the ABI (Application Binary Interface) specification for the compiler/platform. It should document the sizes, alignments, endianness, etc. of the basic primitive types supported.
回答2:
Generic method of sambowry's method (C++):
#include <iostream>
#include <typeinfo>
template <typename T>
void print_sizeof(void)
{
std::cout << "sizeof(" <<
typeid(T).name() << ") == " <<
sizeof(T) << std::endl;
}
int main(void)
{
print_sizeof<short>();
print_sizeof<unsigned int>();
print_sizeof<long>();
print_sizeof<long long>();
print_sizeof<uint64_t>();
}
Note the compiler isn't required to give you an actual string for name, but most do.
回答3:
In general, you don't need to know exact sizes if you include stdint.h
. There are defined several very useful types.
If you want exact size, use these:
int8_t
uint8_t
int16_t
uint16_t
int32_t
uint32_t
int64_t
uint64_t
If you want at least the specified size, use these:
int_least8_t
uint_least8_t
int_least16_t
uint_least16_t
int_least32_t
uint_least32_t
int_least64_t
uint_least64_t
If you want at least the specified size optimized for speed, use these:
int_fast8_t
uint_fast8_t
int_fast16_t
uint_fast16_t
int_fast32_t
uint_fast32_t
int_fast64_t
uint_fast64_t
回答4:
You may query the length of a data type with the sizeof operator. For example:
#include <stdio.h>
#include <inttypes.h>
#define PRINT_SIZEOF(type) printf("sizeof( " #type " ) == %zi\n", sizeof(type) )
int main(void){
PRINT_SIZEOF( short );
PRINT_SIZEOF( unsigned int );
PRINT_SIZEOF( long );
PRINT_SIZEOF( long long );
PRINT_SIZEOF( uint64_t );
}
EDIT: %i changed to %zi
回答5:
You could write a test program that uses sizeof
calls on all the types you're interested in. Might also be useful to check limits.h.
回答6:
you could probably write some simple shell script that prompts for a type and when you enter it it compiles something like what sambowry posted and executes it to tell you what the size of it is..
来源:https://stackoverflow.com/questions/1457431/c-c-size-of-builtin-types-for-various-compilers-platforms