mardi 10 novembre 2020

multiple definition of a variable in c++ [duplicate]

I have 2 source files and 2 header file.

  1. utils.hpp

    #ifndef UTILS_HPP_INCLUDED
    #define UTILS_HPP_INCLUDED
    
    #include <iostream>
    #include <fstream>
    #include <map>
    
    using namespace std;
    int test;
    void display(void);
    
  2. utils.cpp

    #include "utils.hpp"
    
    void display(void)
    {
     test = 1;
     cout << test;
    }
    
  3. main.hpp

     #ifndef MAIN_HPP_INCLUDED
     #define MAIN_HPP_INCLUDED
     #include "utils.hpp"
     #include<iostream>
     using namespace std;
     int i =0;
     #endif // MAIN_HPP_INCLUDED
    
  4. main.cpp

     #include <iostream>
     #include "main.hpp"
    
     using namespace std;
    
     int main()
     {
       display();
       cout << "Hello world!" << endl;
       return 0;
     }
    

what is wrong here? why do i get multiple declaration of the variable?

error:

    test2/utils.hpp:11: multiple definition of `test'; obj\Debug\main.o:C:/Users/test2/utils.hpp:11: first defined here

edited: I did try with extern, i still get the same error.

Aucun commentaire:

Enregistrer un commentaire