c++ 多个cpp包含一个头文件报错

我的头文件仅仅声明了变量,没有定义,为什么还会报这个错误?
clipboard.png

目录结构(两个cpp包含一个头文件):

clipboard.png

head.h:

#ifndef HEAD_H
#define HEAD_H

#include<stdio.h>      /*标准输入输出定义*/
...

#define FALSE 0
#define TRUE 1
...

int fd;
uint8_t recv[1024];
int addr[4];
bool verified;
int frmType;

#endif
阅读 5.2k
2 个回答

在 C++ 里,对于一个变量声明,只要它没有 extern ,或者有 initializer ,那么它就是一个定义。

所以,你贴出的所有在 C++ 里都是定义(definition)。

在多个文件里 include ,就会在多个文件里定义,从而引起重复定义的错误。

======================

在 C 里(因为你还贴了一个 C 标签 ....),它们会被叫做 tentative definition ,最终还是会成为 definition 。

但是,C 标准附录J(Common extensions)里有这样一条:

J.5.11 Multiple external definitions

1 There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).

这一个扩展允许一个变量在多个文件里定义。实现这个扩展的编译器可能并不报错。

=====================

C 与 C++ 是两种不同的语言

main.cpp代码贴一下?猜测main.cpp也定义了。include头文件,相当于把头文件中的代码包在在cpp文件中。除非你在语句前加上extern显示指定这些变量在其它地方定义。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题