c ++变量的多个定义

Bg1*_*987 19 c++ compiler-errors

我有4个文件(2个标题和2个代码文件).FileA.cpp,FileA.h,FileB.cpp,FileB.h

FileA.cpp:

#include "FileA.h"

int main()
{
    hello();
    return 0;
}

void hello()
{
    //code here
}
Run Code Online (Sandbox Code Playgroud)

FileA.h:

#ifndef FILEA_H_
#define FILEA_H_
#include "FileB.h"
void hello();

#endif /* FILEA_H_ */
Run Code Online (Sandbox Code Playgroud)

FileB.cpp:

#include "FileB.h"

void world()
{
    //more code;
}
Run Code Online (Sandbox Code Playgroud)

FileB.h:

#ifndef FILEB_H_
#define FILEB_H_

int wat;
void world();


#endif /* FILEB_H_ */
Run Code Online (Sandbox Code Playgroud)

当我尝试编译(使用eclipse)时,我得到了"wat'的多重定义"并且我不知道为什么,它似乎应该可以正常工作.

Ric*_*III 28

我不打算包含所有细节,但是你wat在编译uint中定义了一个全局变量两次.

要修复,请使用以下命令:

FileB.h

extern int wat;
Run Code Online (Sandbox Code Playgroud)

FileB.cpp

int wat = 0;
Run Code Online (Sandbox Code Playgroud)

this (extern)告诉编译器变量wat存在于某个地方,并且它需要自己找到它(在这种情况下,它在其中FileB.cpp)


Cor*_*lks 9

不要在标头中声明变量.#include从字面上将文件的内容复制并粘贴到另一个文件中(也就是说,任何文件#include "FileB.h"都会将FileB.h的内容直接复制到其中,这意味着int wat在每个文件中都会定义#include "FileB.h").

如果wat要从FileA.cpp 访问,并在FileB.cpp中声明它,可以将其标记为externFileA.cpp.