在哪里声明结构

时间:2019-07-15 20:05:10

标签: c function struct header-files declaration

我已经制作了3个文件来组织代码。 main.c,functions.h和functions.c。我还制作了一种可以与某些函数一起使用的结构,但是我遇到的问题是找不到任何方法来声明使用.h文件中的结构的函数。唯一有效的方法是将函数放入结构的.c中,而没有在.h中声明它们中的任何一个。

我尝试过

主要是:

#include "functions.c"

和.c中的

#include "functions.h"
void myfunction(sinWave *sw, float u, float ts){
};

typedef struct{
   float amplitude;
   float fase;
} sinWave;

在.h中:

typedef struct sinWave;

void myfunction(sinWave *, float, float);

但是它不起作用。我得到:

warning: useless storage class specifier in empty declaration
'typedef struct sinWave;'a

unknown type name 'sinWave'
'void ePLL(sinWave , float , float);'

4 个答案:

答案 0 :(得分:3)

只需按照正常方式进行操作即可

// functions.h
// type declaration
typedef struct { . . . } sinWave;

// function prototype
void myfunction(sinWave *, float, float);

// functions.c
#include "functions.h"

void myfunction(sinWave *sw, float u, float ts) {
   // function definition here
}

答案 1 :(得分:2)

像这样更好:

main.c

#include "functions.h"

int main() {
    // ...
}

functions.h

typedef struct {
    float amplitude;
    float fase;
} sinWave;

void myfunction(sinWave *, float, float);

functions.c

#include "functions.h"

void myfunction(sinWave *sw, float u, float ts) {
    // ...
};

以这种方式构建(假设您将使用sincos等):

gcc -o xyz main.c functions.c -lm

答案 2 :(得分:1)

请勿包含.c,这是非常糟糕的样式,请使其在标题中可见

functions.h中:

typedef struct sinWave sinWave;

void myfunction(sinWave *, float, float);

functions.c中:

#include "functions.h"

struct sinWave {
   float amplitude;
   float fase;
};

void myfunction(sinWave *sw, float u, float ts) {

}

main.c中:

#include "functions.h"

答案 3 :(得分:1)

typedef struct sinWave;未声明类型。它引入了sinWave作为 tag 结构。标签本身不是类型名称。它使struct sinWave成为一种类型,但不是sinWave本身。 (在C ++中,它将使sinWave成为一种类型。)

要解决此问题,您需要进行两项更改。在functions.h中,将sinWave声明为struct sinWave的别名:

typedef struct sinWave sinWave;

在functions.c中,插入带有标签的结构定义:

struct sinWave
{
   float amplitude;
   float fase;
};

(您可能还想正确拼写phase。)

请注意,您已经在function.c中有了结构定义:

typedef struct{
   float amplitude;
   float fase;
} sinWave;

这有两个问题。一个是在一个翻译单元中用标签定义的结构与在另一翻译单元中没有标签定义的结构不兼容。并且您需要使用标记来标识typedef为哪个结构命名(或者您可以在function.h中使用typedef提供该结构的完整定义,但这是一个由于其他原因而导致的不良解决方案。

另一个问题是此定义出现在myfunction之后,但是myfunction可能需要结构的定义,因此该定义必须出现在myfunction之前。

相关问题