我正在开发一个读取 NFC 卡的程序,并且我有一个头文件 source.h,其中包含在其相关源代码 source.c 中使用的所有变量。示例如下:
#ifdef __cplusplus
extern "C" {
#endif
int SDA_SUPPORT_PRESENT = 0;
int DDA_SUPPORT_PRESENT = 0;
int CDA_SUPPORT_PRESENT = 0;
int CARDHOLDER_VERIFICATION_PRESENT = 0;
...
源代码 source.c 包含利用上述定义的变量的方法。示例如图:
#include <source.h>
extern void translateError(uint8 error, int slot) //one of the methods
{
TP_DbgSerialPrn("\n\rDevice Error: ");
switch(error)
{
...
我还有一个源文件 CardReader.c,它调用 source.c 中包含的方法,并且有一个相关的头文件 CardReader.h。问题是,当我将 source.h 文件包含在 CardReader.h 文件中时,出现以下错误:
../CardReader.o:(.bss+0x12b4): first defined here
../source.o:(.bss+0x12b8): multiple definition of `SLOT_NUMBER'
../CardReader.o:(.bss+0x12b8): first defined here
../source.o:(.data+0x49): multiple definition of `LISTED_APPLICATION_IDS'
../CardReader.o:(.data+0x49): first defined here
../source.o:(.data+0xc9): multiple definition of `LISTED_APPLICATION_IDS_LENGTH'
所有其余错误消息都属于同一类型。如 CardReader.h 所示,包含了 source.h 文件:
#include <TPCardReader.h>
#include <source.h>
#ifdef __cplusplus
extern "C" {
#endif
...
把路径变量设置好,这样就可以找到了,然后在CardReader.c中照常调用CardReader.h文件。我的问题是为什么会出现该错误,但我只在 source.h 中定义了每个指定变量一次?是否缺少某些内容或未执行某些操作,或者我不理解该错误?
最佳答案
不应在头文件中定义变量。
您应该在头文件中添加
extern int SDA_SUPPORT_PRESENT;
然后在源(.c)文件中你应该有
int SDA_SUPPORT_PRESENT = 0;
这将确保您只有一个变量定义
但是全局变量又不是一个好主意
关于c - 当我在 source.h 中只定义了每个指定变量一次时,为什么会出现 "multiple definition of"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007743/