我正在尝试创建一个可以计算类的加权平均值的项目。在这个项目中,我决定将头文件的声明和实现分别拆分为.h和.c文件,然后将它们链接为目标文件。直到我创建了我的最新文件(矢量函数库)之前,此方法一直有效。当我尝试构建项目时,vector.h中的功能签名与vector.c中的功能签名冲突。这些是文件:
vector.h:
#ifndef VECTOR_H
#define VECTOR_H
void vector_initiate_float(Vector_float *vector);
void vector_append_float(Vector_float *vector, int value);
int vector_get_float(Vector_float *vector, int index);
void vector_set_float(Vector_float *vector, int value, int index);
void vector_double_cap_if_full_float(Vector_float *vector);
void vector_free_float(Vector_float *vector);
#endif /* VECTOR_H */
vector.c:
#include <stdio.h>
#include <stdlib.h>
#include "constants.h"
#include "vector.h"
void vector_append_float(Vector_float *vector, float value){
vector_double_cap_if_full_float(vector);
vector->data[vector->size++] = value;
}
float vector_get_float(Vector_float *vector, int index){
if (index >= vector->size || index < 0) {
printf("Index %d out of bounds for vector of size %d\n", index, vector->size);
exit(1);
}
return vector->data[index];
}
void vector_set_float(Vector_float *vector, int index, float value){
while (index >= vector->size) {
vector_append_float(vector, 0);
}
// set the value at the desired index
vector->data[index] = value;
}
void vector_double_cap_if_full_float(Vector_float *vector){
if (vector->size >= vector->capacity) {
// double vector->capacity and resize the allocated memory accordingly
vector->capacity *= 2;
vector->data = realloc(vector->data, sizeof(int) * vector->capacity);
}
}
void vector_free_float(Vector_float *vector){
free(vector->data);
}
当我运行gcc -c vector.c时输出
vector.c:14:6: error: conflicting types for ‘vector_append_float’
void vector_append_float(Vector_float *vector, float value){
^~~~~~~~~~~~~~~~~~~
In file included from vector.c:11:
vector.h:14:6: note: previous declaration of ‘vector_append_float’ was here
void vector_append_float(Vector_float *, int);
^~~~~~~~~~~~~~~~~~~
vector.c:19:7: error: conflicting types for ‘vector_get_float’
float vector_get_float(Vector_float *vector, int index){
^~~~~~~~~~~~~~~~
In file included from vector.c:11:
vector.h:16:5: note: previous declaration of ‘vector_get_float’ was here
int vector_get_float(Vector_float *, int);
^~~~~~~~~~~~~~~~
vector.c:27:6: error: conflicting types for ‘vector_set_float’
void vector_set_float(Vector_float *vector, int index, float value){
^~~~~~~~~~~~~~~~
In file included from vector.c:11:
vector.h:18:6: note: previous declaration of ‘vector_set_float’ was here
void vector_set_float(Vector_float *, int, int);
如您所见,即使我项目中的其他任何.c和.h文件都没有发生这种情况,两个文件上的函数定义似乎彼此冲突。搜索互联网没有任何结果,因此我在这里发布。
答案 0 :(得分:4)
在错误消息状态下,指定的函数的声明与其定义之间存在冲突。具体来说:
vector_append_float
的第二个参数为float
,但声明显示int
。vector_get_float
返回float
,但是声明说它返回int
。vector_set_float
为第三个参数加上了float
,但声明中说它应该是int
。函数的声明和定义需要匹配。由于定义似乎使用了正确的类型,因此您需要更新头文件中的声明以使其匹配。