c ++变量的多个定义 [英] c++ multiple definitions of a variable

查看:168
本文介绍了c ++变量的多个定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



FileA.cpp:

  #includeFileA.h

int main()
{
hello
return 0;
}

void hello()
{
// code here
}

FileA.h:

  #ifndef FILEA_H_ 
# define FILEA_H_
#includeFileB.h
void hello();

#endif / * FILEA_H_ * /

FileB.cpp:

  #includeFileB.h

void world()
{
//更多代码
}

FileB.h:

  #ifndef FILEB_H_ 
#define FILEB_H_

int wat;
void world();


#endif / * FILEB_H_ * /

尝试编译(使用eclipse),我得到wat'的多重定义
我不知道为什么,它似乎应该工作很好。

解决方案

我不会包括所有的细节,但你定义一个全局变量, wat



FileB.h 要修复,

  extern int wat; 

FileB.cpp

  int wat = 0; 

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


I have 4 files (2 headers, and 2 code files). FileA.cpp, FileA.h, FileB.cpp, FileB.h

FileA.cpp:

#include "FileA.h"

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

void hello()
{
    //code here
}

FileA.h:

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

#endif /* FILEA_H_ */

FileB.cpp:

#include "FileB.h"

void world()
{
    //more code;
}

FileB.h:

#ifndef FILEB_H_
#define FILEB_H_

int wat;
void world();


#endif /* FILEB_H_ */

when I try to compile(with eclipse), I get " multiple definition of `wat' " And I don't know why, it seems as it should work just fine.

解决方案

I'm not going to include all of the details, but you define a global variable, wat twice in your compilation uint.

To fix, use the following:

FileB.h

extern int wat;

FileB.cpp

int wat = 0;

This (extern) tells the compile that the variable wat exists somewhere, and that it needs to find it on it's own (in this case, it's in FileB.cpp)

这篇关于c ++变量的多个定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆