【发布时间】: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)) ===|
编辑:我不知道这与你们所说的其他问题有什么关系。那么我如何才能完成这项工作,这就是我需要知道的全部内容
【问题讨论】:
-
当你包含一个头文件时,它会被复制到包含文件中。包含保护将阻止它多次包含在单个编译文件中,但不能阻止包含在多个编译文件中(这会很糟糕。想想如果项目中只有一个文件可以包含
<strng>会发生什么情况@ )。当您在标题中定义变量和函数时,包含标题的所有内容都会获得这些定义的副本。即时多个定义。 -
A:...goto A是一个while (true) { ... }循环[有一堆额外的陷阱和事情可能出错的方式。 Prefer thewhileloop. -
改变你的设计模式。我推荐这个简单的规则:头文件中的函数原型,源文件中的函数定义。此规则的例外是内联函数。
标签: c++