C语言药房管理系统拆分多C文件头文件多重声明报错如何解决
问题原因
头文件中直接定义了全局变量与字符串常量指针,C语言中#include的本质是将头文件内容原样插入到引用位置,每一个引用该头文件的C文件都会独立生成一份这些变量的实例,链接阶段多个重复的符号就会触发多重声明错误。单文件编译时只有一份实例,因此不会触发报错。
修复方案
方法1(标准推荐写法)
- 修改头文件,将所有变量定义改为
extern声明,移除初始化逻辑,结构体、函数原型、宏定义无需修改:
extern const char* medicine_format; extern const char* supplier_format; extern const char* customer_format; #define SIZE 20 extern char coup[SIZE]; extern float dis;
- 选择任意一个C文件(推荐主函数所在C文件,也可新建
common.c统一存放公共变量),单独完成这些变量的定义与初始化:
#include "MAINPROJECTNIKLASLOREK_H_" const char* medicine_format ="\n\tMediID:%s\n\tMediName:%s\n\tQuantity:%d\n\tPrice:%.2f \n\tExp.Date:%s\n\tCompany:%s\n\tSupplier:%s\n\tInfo:%s\n"; const char* supplier_format = "\n\tSupplierID:\t%s\n\tSupplierName:\t%s\n\tMobileNumber: \t%s\n\tCompany:\t%s\n"; const char* customer_format = "\n\tCustomerID:\t%s\n\tCustomerName:\t%s\n\tMobileNumber: \t%s\n"; char coup[SIZE]={'n','o','c','o','u','p'}; float dis = 1.00;
- 重新编译所有C文件即可解决冲突。
方法2(小项目快速修复)
如果项目体量小,不想单独管理公共变量,可以直接将头文件中的这些变量定义前加上static关键字:
static const char* medicine_format ="\n\tMediID:%s\n\tMediName:%s\n\tQuantity:%d\n\tPrice:%.2f \n\tExp.Date:%s\n\tCompany:%s\n\tSupplier:%s\n\tInfo:%s\n"; static const char* supplier_format = "\n\tSupplierID:\t%s\n\tSupplierName:\t%s\n\tMobileNumber: \t%s\n\tCompany:\t%s\n"; static const char* customer_format = "\n\tCustomerID:\t%s\n\tCustomerName:\t%s\n\tMobileNumber: \t%s\n"; static char coup[SIZE]={'n','o','c','o','u','p'}; static float dis = 1.00;
这种写法会让每个C文件生成一份仅当前文件可见的变量副本,不会触发链接冲突,但会额外占用少量内存,仅适合小型项目使用。
内容的提问来源于stack exchange,提问作者Loreenik
相关产品推荐
相关产品推荐

