【问题标题】:Why is "multiple definition of" error coming up, when I have only defined each of the specified variables once in source.h? [duplicate]当我在 source.h 中只定义了每个指定的变量时,为什么会出现“多重定义”错误? [复制]
【发布时间】:2015-03-16 11:04:57
【问题描述】:

我正在开发一个读取 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。问题是,当我在 CardReader.h 文件中包含 source.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'

所有其余的错误消息都属于同一类型。 source.h 文件包含在 CardReader.h 中:

#include <TPCardReader.h> 
#include <source.h>

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

正确设置路径变量,这样就可以找到,然后在CardReader.c中照常调用CardReader.h文件。我的问题是为什么会出现这个错误,但我只在 source.h 中定义了每个指定的变量?是否有遗漏或未做或我不理解错误?

【问题讨论】:

  • 请写一个更好的标题。您能用 10 个字左右总结您提出的问题,并将其放在标题中吗?
  • 我已经为你修好了。

标签: c


【解决方案1】:

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

而不是在你应该有的头文件中

extern int SDA_SUPPORT_PRESENT;

然后在你应该有的源 (.c) 文件中

int SDA_SUPPORT_PRESENT = 0;

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

但话说回来,全局变量是个坏主意

【讨论】:

  • 正如我从其他重复的问题中读到的,您甚至无法在头文件中指定数组大小。如果我想要一个大小为 16 的数组但只指定前 3 个索引值怎么办?例如整数样本 [16] = {0, 1, 2}。我该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 2012-04-15
相关资源
最近更新 更多