在header和c文件中定义typedef结构

时间:2014-05-09 10:56:23

标签: c struct typedef

我正在尝试为即时制作的东西定义一个新类型,这是准系统版本:

vectors.h

#ifndef HEADER_GUARD_VECTORS
#define HEADER_GUARD_VECTORS

typedef struct {
    double x;
    double y;
    double z;
    vector2 operator=(vector2 vector);
}
double vector2_get_angle(vector2 vector);
#endif

vectors.c

#include <math.h>

#define PI 3.14159265

typedef struct {
    double x;
    double y;
    inline vector2 operator=(vector2 value)
    {
        x = value.x;
        y = value.y;
        return value;
    }
} vector2;

double vector2_get_angle(vector2 vector)
{
    return atan2(vector.y,vector.x) * (180.0 / PI);
}

test.c的

#include <stdio.c>
#include "vectors.h"

int main(int argc, const char* argv[])
{
    printf("Hello World\n");
    vector2 vec = {x=1, y=2};
    printf("Vector: %d, %d ",vec.x,vec.y);
    printf(" has an angle of %d degrees\n",vector2_get_angle(vec));
    return 0;
}

生成文件

CFLAGS = -Wall -lm -lc -lgcc

all: test

test: vectors.o test.o
    gcc test.o vectors.o -o test

test.o: test.c
    gcc -c $(CFLAGS) test.c

vectors.o: vectors.c
    gcc -c $(CFLAGS) vectors.c

进行命令反馈

$ make
gcc -c -Wall -lm -lc -lgcc vectors.c
vectors.c:8:2: error expected specifier-qualifier-list before ?inline?
vectors.c:20:33: warning: ?struct vector2? declared inside parameter list [enabled by default]
vectors.c:20:33: warning: its scope is only this definition or declaration, which is probably not what you want [enabled by default]
vectors.c:20:41: error: parameter 1 (?vector?) has incomplete type
vectors.c: In function ?vector2_get_angle?:
vectors.c:23:1: warning: control reaches end of non-void function [-Wreturn-type]

现在我的主要问题是:

如何在header和vectors.c源文件中正确定义类型,以便我可以像test.c中所示使用它。

感谢您阅读我的问题

1 个答案:

答案 0 :(得分:1)

  

如何在header和vectors.c源文件中正确定义类型,以便我可以像test.c中所示使用它。

您必须使用正确的编程语言编写它。您的代码在C中无效,因为它不支持运算符重载或任何其他C ++功能。

此外,内嵌关键字是在C99标准中引入的,因此您必须使用-std=c99进行编译。

此外,typedef struct {}需要在结尾处以类型名称结束。

此外,vector2未在头文件的范围内定义。