编译时出现Conflicting types错误:类型一致仍报错
解决‘skirt’存在冲突类型的编译错误
问题原因
在C语言中,函数调用前必须让编译器知晓其返回类型和参数信息。你的代码里main函数先调用了skirt,但skirt的定义放在main之后,编译器遇到skirt调用时会默认它的返回类型是int,可后续实际定义的返回类型是int64,这就造成了类型冲突错误。
两种解决方法
方法一:提前声明skirt函数
在main函数之前添加skirt的函数声明,让编译器提前知道函数的类型信息:
#include <time.h> #include <stdio.h> #include <math.h> #include <stdint.h> typedef long long int64; // 函数声明 int64 skirt(const struct timespec after, const struct timespec before); int main() { struct timespec iter_start, iter_end; clock_gettime(CLOCK_MONOTONIC, &iter_start); // iteracijai pirmai printf("hello"); clock_gettime(CLOCK_MONOTONIC, &iter_end); int64 duration = skirt(iter_end, iter_start); return(0); } int64 skirt(const struct timespec after, const struct timespec before) { return ((int64)after.tv_sec - (int64)before.tv_sec) * (int64)1000000 + ((int64)after.tv_nsec - (int64)before.tv_nsec) / 1000; }
方法二:调整函数顺序,把skirt定义移到main之前
直接将skirt函数的整个定义放在main函数前面,这样编译器会先读取到函数的完整定义,调用时就不会出现类型误解:
#include <time.h> #include <stdio.h> #include <math.h> #include <stdint.h> typedef long long int64; int64 skirt(const struct timespec after, const struct timespec before) { return ((int64)after.tv_sec - (int64)before.tv_sec) * (int64)1000000 + ((int64)after.tv_nsec - (int64)before.tv_nsec) / 1000; } int main() { struct timespec iter_start, iter_end; clock_gettime(CLOCK_MONOTONIC, &iter_start); // iteracijai pirmai printf("hello"); clock_gettime(CLOCK_MONOTONIC, &iter_end); int64 duration = skirt(iter_end, iter_start); return(0); }
内容的提问来源于stack exchange,提问作者Aer
相关产品推荐
相关产品推荐

