读书人

struct 声明放在.h定义在.c中出现

发布时间: 2012-02-06 15:52:45 作者: rapoo

struct 声明放在.h,定义在.c中,出现struct不可用的情况
如果我把struct的定义和声明都放在.h中,在其他.c文件中使用这个struct是没有任何问题,但如果声明放在.h,定义在.c中,其他.c文件调用struct就会编译出错,各位有知道是为什么的么?

test.h
---------------------------------------------
#ifndef COMM_H
#define COMM_H

#include <stdio.h>
#include <stdlib.h>

struct test_st;
typedef struct test_st test_t;

void test();
#endif
----------------------------------------------

test.c
----------------------------------------------
#include "test.h "

struct test_st
{
int count;
char name[10];
};

----------------------------------------------

test2.c
----------------------------------------------
#include "test.h "

void test()
{
test_t t;
}

----------------------------------------------

编译时会报错:
----------------------------------------------
test2.c: In function `void test() ':
test2.c:5: aggregate `test_t t ' has incomplete type and cannot be defined
test2.c:5: warning: unused variable ` <typeprefixerror> t '
-----------------------------------------------



[解决办法]
把test1 include进去

struct test_st; 没什么用 去掉
[解决办法]
test.h
---------------------------------------------
#ifndef COMM_H
#define COMM_H

#include <stdio.h>
#include <stdlib.h>

//struct test_st; //注释掉这行
typedef struct test_st test_t;
struct test_st
{
int count;
char name[10];
};

void test();
#endif
----------------------------------------------

test.c
----------------------------------------------
#include "test.h "

void test()
{
test_t t;
}

----------------------------------------------
[解决办法]
不允许这样做吧
#include预编译指令就是把.h文件的内容地当作一段文本嵌入到.c内,一个.c文件(一个.c文件对编译器来说就是一个可独立编译的单元)内不能存在未定义的类型,因为如果类型未定义的话编译器独立编译它的时候显然不知道要为每个该类型的对象分配多大的内存空间,但是允许有未定义的函数,因为对于函数调用而言编译器仅仅需要知道一个函数地址就可以了,而这个工作可以到连接时再作,所以就允许编译器有未定义的函数,但是连接时如果存在未定义的函数就会报错!!

对于test2.c而言,它是一个可以独立编译的实体,对它的编译不会参照其他任何可独立编译单元,所以编译器对其进行独立编译的时候,无法获得struct test_st类型的具体信息就会报错!!!

要解决此问题 楼上正解!

读书人网 >C语言

热点推荐