代码: 全选
1.c
unsigned char verify(unsigned char data[], unsigned char length)
{
unsigned char result = 0;
for (int i = 0; i < length; i++) {
result += data[i];
}
result += 0x5a;
return result;
}
代码: 全选
2.c
#include <stdio.h>
//unsigned char verify(unsigned char data[], unsigned char length);
int main()
{
unsigned int a;
unsigned char b[5] = {0x35, 0x5b, 0x5c, 0x5d, 0x5e};
a = verify(b, 5);
printf("%d\n", a);
return 0;
}
再将2.c编译链接liba.so,verify函数返回的应当是0-255的数,但是返回的是257,最后打印出来的是257。
如果将1.c编译时去除优化:gcc -Wall 1.c -o liba.so -shared -std=gnu99 -O0
再用2.c编译的程序执行就正确了,返回1。
如果1.c仍然用-O3编译,在2.c中声明语句前的注释去掉,编译的结果却是正确的,返回1。
在gcc4.7.2和4.8.1中都有这个错误,不知是不是我的代码有什么问题么。(我是在用Python调用动态库的时候发现这个问题的)