关于C#:当我仅在source.h中定义每个指定变量一次时,为什么会出现“多重定义”错误?


Why is “multiple definition of” error coming up, when I have only defined each of the specified variables once in source.h?

本问题已经有最佳答案,请猛点这里访问。

我正在开发一个程序来读取NFC卡,并且有一个头文件source.h,其中包含要在其相关源代码source.c中使用的所有变量。示例如下所示:

1
2
3
4
5
6
7
8
9
#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包含利用上述定义的变量的方法。示例如下所示:

1
2
3
4
5
6
7
8
9
10
#include <source.h>

extern void translateError(uint8 error, int slot) //one of the methods
{
    TP_DbgSerialPrn("

Device Error:"
);
    switch(error)
    {
...

我还有一个源文件CardReader.c,该文件调用source.c中包含的方法,并且具有一个相关的头文件CardReader.h。问题是,当我在CardReader.h文件中包含source.h文件时,出现以下错误:

1
2
3
4
5
6
../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文件:

1
2
3
4
5
6
7
#include <TPCardReader.h>
#include <source.h>

#ifdef __cplusplus
extern"C" {
#endif
...

正确设置路径变量,以便可以找到它,然后照常在CardReader.c中调用CardReader.h文件。我的问题是为什么会出现该错误,但是我只在source.h中定义了每个指定变量一次?是否缺少某些内容或没有执行该操作,或者我不理解该错误?


不应在头文件中定义变量。

相反,您应该在头文件中

1
extern int SDA_SUPPORT_PRESENT;

然后在源(.c)文件中

1
int SDA_SUPPORT_PRESENT = 0;

这将确保您只有一个变量定义

但是再说一次全局变量是个坏主意