前几天在定位问题时发现一个奇怪的现象,在同文件中访问指针正常,跨文件访问直接发生段错误。经过一轮排查终于发现64位系统中跨文件调用未声明函数的指针型返回值被截断位32位。定位过程中一直用%x打印指针,而没有正确的使用%p,一直没有发现指针高32位被截断。
下面是一个简单的例子。
main.c
#include <stdio.h>
#include "hello_world.h"
#include "hello_yihelsc/hello_yihelsc.h"
int main()
{
printf("begin run \n");
long ret = HelloWorld();
printf("HelloWorld return %lx \n", ret);
ret = HelloYihelsc();
printf("HelloYihelsc return %lx \n", ret);
return 0;
}
hello_world.h
#ifndef __HELLO_WORLD__
#define __HELLO_WORLD__
long HelloWorld();
#endif
hello_world.c
#include <stdio.h>
#include "hello_world.h"
long HelloWorld()
{
printf("Hello World \n");
return 0x123456789abcdef0;
}
hello_yihelsc.h
我们把函数声明去掉。
#ifndef __HELLO_LSC__
#define __HELLO_LSC__
//long HelloYihelsc();
#endif
hello_yihelsc.c
#include <stdio.h>
#include "hello_yihelsc.h"
long HelloYihelsc()
{
printf("Hello Yihelsc \n");
return 0xfedcba9876543210;
}
运行结果:
这个案例的第二个警示,编译告警还是要清零的。
gitcode链接: