【问题标题】:Multiple definitions of 'some variable' which is declared in a header file在头文件中声明的“某些变量”的多个定义
【发布时间】:2021-11-29 21:08:46
【问题描述】:

我有一个头文件command.h,其中包含我所有的变量和函数声明

//command.h 

int someVar1; 
int someVar2;
void modifying_loop (int a, int b);
int someVar3;
.
.
.

在另一个文件my_algorithm.c中我定义了之前声明的函数modifying_loop并使用了一些在头文件中声明的变量

//my_algorithm.c

#include "command.h"
void modifying_loop (int x, int y)
{
    someVar1 = x+2;
    someVar2 = y+2;
}

我有我的主文件command.c 我这样调用modifying_loop 函数:

#include "command.h"
int main ()
{
    modifying_loop(5,6);
    return 0;
}

我使用返回我的gcc -o command command.c -lm -lpigpio -L/usr/lib/ 编译它

undefined reference to modifying_loop'

然后解决我使用链接my_algorithm.c文件

gcc -o command command.c my_algorithm.c -lm -lpigpio -L/usr/lib/ 这给了我以下信息:

/usr/bin/ld: /tmp/cc6ad5oo.o:(.bss+0x3c18): multiple definition of `someVar1'; /tmp/ccaydPyq.o:(.bss+0x24918): first defined here
/usr/bin/ld: /tmp/cc6ad5oo.o:(.bss+0x3c1c): multiple definition of `someVar2'; /tmp/ccaydPyq.o:(.bss+0x2491c): first defined here

以及头文件中声明的其余变量的相同错误。有谁知道是什么导致了错误。

【问题讨论】:

  • someVar1someVar2 是干什么用的?您可能需要在 command.h 中将它们声明为 extern,然后在其中一个 .c 文件中定义它们。但是它们是全局变量,这通常是个坏主意。
  • "函数在头文件中定义并在另一个c文件中声明" --> 我想你希望"函数在头文件中声明并且定义 在另一个 c 文件中”。
  • 请更新问题标题以反映真正的问题,即“多重定义”问题,因为您已经有了解决“未定义引用”问题的正确方法。
  • 在.h文件中,void modifying_loop (int a, int b)之后,有';''{"还是什么?
  • this 的副本,并与 thisthisthis 相关。

标签: c


【解决方案1】:
/usr/bin/ld: /tmp/cc6ad5oo.o:(.bss+0x3c18): multiple definition of `someVar1'; /tmp/ccaydPyq.o:(.bss+0x24918): first defined here
/usr/bin/ld: /tmp/cc6ad5oo.o:(.bss+0x3c1c): multiple definition of `someVar2'; /tmp/ccaydPyq.o:(.bss+0x2491c): first defined here

您必须确保不会多次包含相同的代码。 您可以通过在#ifndef #define #endif 宏中嵌入头文件代码来做到这一点。这些被称为include guards

您的其余代码似乎工作正常。

【讨论】:

  • 没有证据表明标头在单个翻译单元的编译中被多次包含。实际问题很可能是显示的声明是编译器将其视为完整定义的暂定定义,因此相同的标识符在不同的翻译单元中定义了两次。 (这是 GCC 行为的最新变化,从版本 10 开始;之前的暂定定义导致合并通用符号而不是常规定义。)解决方案是将它们标记为 extern 并将常规定义放在一个源文件中。跨度>
  • @Eric Postpischil,是的,大多数编译器都会发出关于守卫的警告,因为它没有包含在错误列表中,我们没有任何证据表明用户已经没有添加这些。
猜你喜欢
  • 2013-08-04
  • 1970-01-01
  • 2018-01-31
  • 2010-11-12
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-10
相关资源
最近更新 更多