1.结构体可以在.c .h文件中多次声明,不能多次定义
2.不要在头文件中进行变量定义。在a.h中定义了变量str,当main.c和func.c文件都包含a.h,预处理器会把a.h分别附到两个源文件开头,相当于在main.c和func.c中重复定义了str全局变量。编译没问题,编译完开始link时,linker会发现main.obj和func.obj中都有str符号,于是报错,这跟C命名冲突是同一情况。
2.如:typedef声明结构标记str后,再用str声明结构变量,会层次分明
程序:
main.c:
/*主函数*/
#include <stdio.h>
#include "a.h"
//#include "func.c" //加入此声明会报错error LNK1169: one or more multiply defined symbols found
//cps student; //在.c 中对结构体的定义
int main()
{
printf("Hello!\n");
input();
pw(student.name);
printf(" age:%d\n score:%0.1lf\n\n", student.age, student.score);
return 0;
}
func.c:
/*函数功能实现*/
#include "a.h"
//#include <stdio> //不声明会警告,不会报错
//cps student;//在.c 中对结构体的定义
void input()
{
printf("age:");
scanf("%d", &student.age);
printf("\nname:");
scanf(" %c", &student.name);
printf("\nscore:");
scanf("%lf", &student.score);
}
int pw(char c)
{
return printf("\n %c的录入信息如下:\n", c);
}
a.h:
/*头文件*/
#ifndef A_H_INCLUDED
#define A_H_INCLUDED
typedef struct
{
int age;
char name;
double score;
} cps; //在头文件中只能对结构体的进行类型定义和实体声明
//对于用到该结构体的 .c 要进行实体定义
cps student;//在.h中对student声明一次或者在两个.c 文件中分别声明,或者在三个文件中都进行声明,不然会报错未声明
void input(); //对函数的声明
int pw(char c); //函数声明
#endif