如何根据操作系统的位数(32或64)来定义输出?我使用了int64_t,使用printf输出一个int64_t整数时,对于32位系统,应使用%lld,对于64位系统,应使用%ld。
我想将输出格式修饰符采用宏定义的方式事先定义好,Linux下貌似可以这样定义:
#if __WORDSIZE == 64
#define FDFS_INT64_FORMAT "%ld"
#else
#define FDFS_INT64_FORMAT "%lld"
#endif
但这样定义是不能跨平台的。
我试过如下定义:
#if sizeof(int64_t) == 8
#define FDFS_INT64_FORMAT "%ld"
#else
#define FDFS_INT64_FORMAT "%lld"
#endif
gcc报错。
我想到一个办法是在Makefile中自动检测操作系统的位数,然后通过-D来定义一个宏。
请问大家,有没有更好的办法?有个疑问,int64_t,不总是64位的么?没有用过,只是觉得看其字面,应该总是64位才对吧。与其去寻找系统的字长,不如为自己的数据设置一个合适的固定长度的整数类型#include <stdint.h>
#include <stdio.h>
static int64_t i64;
static int32_t i32;
static int16_t i16;
static int8_t i8;
void op8() {i8 = 1;}
void op16() {i16 = 1;}
void op32() {i32 = 1;}
void op64() {i64 = 1;}
int getWordlength()
{
int d8, d16, d32, d64;
d8 = &op16 - &op8 - 5;
d16 = &op32 - &op16 - 5;
d32 = &op64 - &op32 - 5;
d64 = (char *)&getWordlength - (char *)&op64 - 5;
if (d16 == 2 * d8) return 8;
else if (d32 == 2 * d16) return 16;
else if (d64 == 2 * d32) return 32;
else return 64;
}
int main()
{
printf("Word length: %d\n", getWordlength());
return 0;
}
原帖由 ivhb 于 2008-9-11 18:24 发表 http://bbs.chinaunix.net/images/common/back.gif
有个疑问,int64_t,不总是64位http://www.easymjm.com的么?没有用过,只是觉得看其字面,应该总是64位才对吧。
这个类型的确会保证是64位。我的问题是如何格式化输出:对于32位系统,应使用%lld,对于64位系统,应使用%ld。
我要根据操作系统的位数来选择是用%lld还是%ld,想通过宏定义的方式解决这个问题。
如果通过程序(非宏定义)方式实现,那是没有任何问题的。sizeof(int) * 8
原帖由 xiaonanln 于 2008-9-11 18:53 发表 http://bbs.chinaunix.net/images/common/back.gif
#include
#include
static int64_t i64;
static int32_t i32;
static int16_t i16;
static int8_t i8;
void op8() {i8 = 1;}
void op16() {i16 = 1;}
void op32() {i32 = ... 我后来是通过shell来实现的。通过shell自动生成一个头文件fdfs_os_bits.h,头文件中通过宏OS_BITS来定义操作系统的位数(32或者64)。在Linux中已经调试通过。
shell代码片断如下http://www.beneficials.net:
tmp_src_filename=fdfs_check_bits.c
cat <<EOF > $tmp_src_filename
#include <stdio.h>
int main()
{
printf("%d\n", sizeof(long));
return 0;
}
EOF
cc $tmp_src_filename
bytes=`./a.out`
请教一个c语言发送邮件的问题/>/bin/rm -fa.out $tmp_src_filename
if [ "$bytes" -eq 8 ]; then
OS_BITS=64
else
OS_BITS=32
fi
cat <<EOF > common/fdfs_os_bits.h
#ifndef _FDFS_OS_BITS
#define _FDFS_OS_BITS
#define OS_BITS$OS_BITS
#endif
EOF#ifdef _WIN64
#ifdef _WIN32
linux下就不知道了原帖由 happy_fish100 于 2008-9-11 19:00 发表 http://bbs.chinaunix.net/images/common/back.gif
这个类型的确会保证是64位。我的问题是如何格式化输出:对于32位系统,应使用%lld,对于64位系统,应使用%ld。
我要根据操作系统的位数来选择是用%lld还是%ld,想通过宏定义的方式解决这个问题。
如果通过 ...
long long类型实现上都是64位的吧。为啥不简化一下?
一律 printf ("%lld", (long long) xxx);
和位数还有关系么?回复 #1 happy_fish100 的帖子你用uname -a,然后去cut,就能得出来操作系统的位数啦,然后通过宏来搞定。