C++中的链接多重包含

问题描述

我使用 3 个文件编写了 C++ 代码。以下是文件名及其整体结构:

graph.h:

#ifndef GRAPH_H
#define GRAPH_H

/*some header files included here*/

using namespace std;
const int max = 1000;
int var;

/*class Graph defined here*/

#endif
graph.cpp:

#include "graph.h"
/*class Graph functions implemented here*/
main.cpp:

#include "graph.h"
using namespace std;
/*main() function implemented here*/

我使用以下命令来编译代码

g++ -std=c++11 -Wno-deprecated -O3 -c  main.cpp
g++ -std=c++11 -Wno-deprecated -O3 -c  graph.cpp
g++ -O3  main.o graph.o -o myProg

前两个命令运行正常,但第三个命令(链接步骤)产生以下错误

graph.o:(.bss+0x0): multiple deFinition of `var'
main.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

我在 graph.h 中使用了标题保护。另外,如果我从“graph.cpp”和“main.cpp”中删除“graph.h”,那么这些文件将无法编译。请帮我弄清楚我做错了什么。非常感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)