【问题标题】:Why is there an "Multiple Definitions" error [duplicate]为什么会出现“多重定义”错误 [重复]
【发布时间】:2019-07-09 03:15:23
【问题描述】:

我试图将 2 个 .cpp 文件与 1 个 .h 文件一起使用,但每当我在两个 .cpp 文件中包含 .h 文件时,我都会收到“多重定义”错误。所以我做了这个来显示我的问题,是的,我知道 thing.cpp 从不做任何事情,但这仍然会引发问题 如果有帮助,我还会使用 Code::Blocks 和 GNU GCC 编译器。

main.cpp

#include <iostream>
#include <C:\0w0\Multiple file test\Hello_world.h>
#include <windows.h>
using namespace std;
int main()
{
    A:
    Sleep(500);
    Hello();
    x++;
    if(x==5)
    {
        Sleep(500);
        Hello();
        return -1;
    }
    goto A;
}

东西.cpp

#include <iostream>
#include <C:\0w0\Multiple file test\Hello_world.h>
#include <windows.h>
using namespace std;
int thing()
{
    A:
    Sleep(500);
    Hello();
    x++;
    if(x==5)
    {
        Sleep(500);
        Hello();
        return -1;
    }
    goto A;
}

hello_world.h

#ifndef Hello_World_H
#define Hello_World_H
#endif // Hello_World
int x=1;
using namespace std;
int Hello()
{
    cout << x << endl;
    return 69;
}

我希望它可以正常工作,但它没有,我收到这些错误

obj\Debug\thing.o||In function 'Z5Hellov':|
C:\0w0\Multiple file test\Hello_world.h|7|multiple definition of 'Hello()'|
obj\Debug\main.o:C:\0w0\Multiple file test\Hello_world.h|7|first defined here|
obj\Debug\thing.o||In function 'Z5Hellov':|
C:\0w0\Multiple file test\Hello_world.h|7|multiple definition of 'x'|
obj\Debug\main.o:C:\0w0\Multiple file test\Hello_world.h|7|first defined here|
||error: ld returned 1 exit status|
||=== Build failed: 5 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

编辑:我不知道这与你们所说的其他问题有什么关系。那么我如何才能完成这项工作,这就是我需要知道的全部内容

【问题讨论】:

  • 当你包含一个头文件时,它会被复制到包含文件中。包含保护将阻止它多次包含在单个编译文件中,但不能阻止包含在多个编译文件中(这会很糟糕。想想如果项目中只有一个文件可以包含 &lt;strng&gt; 会发生什么情况@ )。当您在标题中定义变量和函数时,包含标题的所有内容都会获得这些定义的副本。即时多个定义。
  • A: ... goto A 是一个 while (true) { ... } 循环[有一堆额外的陷阱和事情可能出错的方式。 Prefer the while loop.
  • 改变你的设计模式。我推荐这个简单的规则:头文件中的函数原型,源文件中的函数定义。此规则的例外是内联函数。

标签: c++


【解决方案1】:

hello_world.h : #endif 必须在文件末尾,避免重复定义。

#ifndef Hello_World_H
#define Hello_World_H

int x=1;
using namespace std;
int Hello()
{
    cout << x << endl;
    return 69;
}
#endif // Hello_World

【讨论】:

  • #if/#endif 守卫仅适用于每个编译单元。由于这里使用了两个源文件,所以它不起作用。所以你的答案是错误的。
  • 你把它放在最后是行不通的。得到同样的错误
猜你喜欢
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 2011-04-14
  • 2022-01-22
相关资源
最近更新 更多