![](/img/trans.png)
[英]Dev C compiles this code, but during file creation gives err 3221225477
[英]C code compiles only when I include .c file
當我嘗試編譯代碼時,它僅在我在 Dictionary.c 中包含 Object.c 時才起作用。 作為我的硬件的一部分,我不能更改 Dictionary.h 和 main,也不能在 .h 文件中聲明結構。 你能建議修復嗎?
對象.h
#ifndef __OBJECT_H
#define __OBJECT_H
typedef struct Object Object;
Object createObject (int key, int value);
int getKey (Object object);
int getValue (Object object);
int isSmaller (Object x, Object y);
#endif
對象.c:
#include "object.h"
struct Object
{
int key;
int value;
};
Object createObject (int key, int value)
{
Object object = {key,value};
return object;
}
int getKey (Object object)
{
return object.key;
}
int getValue (Object object)
{
return object.value;
}
int isSmaller (Object x, Object y)
{
if (x.key < y.key)
return 1;
return 0;
}
字典.c
#include <stdio.h>
#include <stdlib.h>
#include "object.h"
#include "object.c"
#include "dictionary.h"
struct Dictionary
{
Object* array;
int sizeOfArray;
int numOfObjects;
};
您不能在沒有首先定義結構的情況下將變量或字段聲明為結構。 那是因為編譯器需要知道它的大小(以及字段的偏移量,如果你使用這些),這需要定義。
但是,聲明指向尚未定義的結構的指針是完全沒問題的,因為編譯器知道指針的大小。 因此,當需要不透明類型時,可以使用基於指向結構的指針的接口,因為這避免了在頭文件中定義結構的需要。
例如,
object.h
:
#ifndef __OBJECT_H
#define __OBJECT_H
typedef struct Object Object;
Object* Object_new(int key, int val);
void Object_delete(Object* object);
int Object_get_key(const Object* object);
int Object_get_val(const Object* object);
int Object_is_smaller(const Object* x, const Object* y);
#endif
object.c
:
#include <stdlib.h>
#include "object.h"
struct Object {
int key;
int val;
};
Object* Object_new(int key, int val) {
Object* object = malloc(sizeof(Object));
if (!object)
return NULL;
object->key = key;
object->val = val;
return object;
}
void Object_delete(Object* object) {
free(object);
}
int Object_get_key(const Object* object) { return object->key; }
int Object_get_val(const Object* object) { return object->val; }
int Object_is_smaller(const Object* x, const Object* y) { return x->key < y->key; }
示例用戶:
#include <stdio.h>
#include "object.h"
int main(void) {
Object* object = Object_new(4, 5);
printf("%d: %d\n",
Object_get_key(object),
Object_get_val(object)
);
Object_delete(object);
return 0;
}
無法在 .h 文件中聲明結構
為什么? .h 文件是定義將由多個 .c 文件使用的結構的正確位置!
將類型定義移至 object.h
#ifndef __OBJECT_H
#define __OBJECT_H
typedef struct Object Object;
// type definition in header file
struct Object
{
int key;
int value;
};
Object createObject (int key, int value);
int getKey (Object object);
int getValue (Object object);
int isSmaller (Object x, Object y);
#endif
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.