我尝试使用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;
}thing.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)) ===|编辑:我不知道这与你们所说的其他问题有什么相似之处。那么我该怎么做呢?这就是我所需要知道的
发布于 2019-07-09 14:23:09
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_Worldhttps://stackoverflow.com/questions/56944835
复制相似问题