mardi 23 février 2021

Linkage multiple inclusion in C++ [duplicate]

I have written a C++ code using 3 files. Here are the file names and their overall structures:

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*/

I use the following commands to compile the code:

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

The first two commands go fine, but the third command (the link step) produces the following error:

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

I have used header guards in graph.h. Also, if I eliminate "graph.h" from "graph.cpp" and "main.cpp" then these files will not compile. Please help me figure out what I am doing wrong. Thank you very much!

Aucun commentaire:

Enregistrer un commentaire