我无法理解c头文件和源文件。我有:
something.c
#include <stdio.h>
#include "something.h"
typedef struct {
int row, col;
} point;
point
whereispoint(point **matrix, int rows, int cols)
{
..... Does something ....
printf("something...");
}
something.h
typedef struct point * p;
p whereispoint(p **matrix, int rows, int cols);
的main.c
#include <stdio.h>
#include "something.h"
int
main(void)
{
int row, col;
p **matrix=malloc(bla, bla);
.....Something.....
p=whereispoint(matrix, row, col);
return 0;
}
现在当我实际上不知道如何编译这个...我试过gcc -c main.c something.c
但这不起作用,我试图单独编译gcc -c main.c
和gcc -c something.c
然后 main.c 有效,但 something.c 不起作用。
我实际上是试图用something.c创建一个库,但由于我甚至无法将其编译为目标代码,所以我不知道该怎么做。我猜在 something.h 中它的struct类型和typedef有问题,但我无法弄清楚是什么......
答案 0 :(得分:2)
在标题中,函数whereispoint()
声明为返回struct point*
(typedef p
),但定义返回struct point
,而不是指针。
就我个人而言,我发现typedef
指针令人困惑,并且如果*
用于表示指针,则认为代码更清晰:
/* header */
typedef struct point point_t;
point_t* whereispoint(point_t** matrix, int rows, int cols);
/* .c */
struct point {
int row, col;
};
point_t* whereispoint(point_t** matrix, int rows, int cols)
{
..... Does something ....
printf("something...");
return ??;
}
答案 1 :(得分:0)
以下内容:
typedef struct {
int row, col;
} point;
键入一个无名结构到类型点。
在something.h中,然后将“struct point”(未定义的结构类型引用)键入“* p”。
通常,您应该在头文件中定义所有“接口类型”,而不是试图隐藏实现(C需要知道实现以访问任何内容)。
尝试在something.h中做这样的事情:
typedef struct point {
int row, col;
} *p;
或者,如果您不确定typedef究竟是如何工作的,只需执行以下操作:
struct point {
int row, col;
}
声明了一种结构类型。