-3

I'm working on a project and I am cleaning my code and Re-doing the code so it's more readable and easy to tweak. I'm having one issue though when I create an object in a header file the complier throws me an error saying its already defined; int assumed. LNK-2005.

I tried creating the objects as 'extern' so I could access the objects from all files that include the file with the specified objects.

// HeaderA.h
#include <Windows.h>

    struct ProcessInfo
    {
         int ProcID;

         HANDLE Handle;

    };

This is header B below

// Header B starts here
// HeaderB.h
#include "HeaderA.h"
{
    ProcessInfo pi;
    pi.ProcID = 10;


    struct Player
    {
        int health = 0;

        float x, y, z;

        int score = 0;
    }
}

Header C This file should be able to use Header B's object 'pi'

//HeaderC.h
#include "HeaderB.h"

// creating object from headerB 
Player player;

// is there a way so I can use the object declared in HeaderB in HeaderC?
// like so
pi.ProcID = 45;

I expected to be able to use the object created in header B through multiple files like HeaderB-HeaderZ. (A-Z; Multiple Headers) But when compiling I get the error "LNK2005 already defined".

Ballers
  • 13
  • 4
  • So basically put the object declaration in a separate header file that's global? and each header file that needs the object simply include the header file is located in? – Ballers Jan 22 '19 at 22:56
  • Yes, for instance, plus one source file where the object is actually defined (and not just declared). – Matthieu Brucher Jan 22 '19 at 22:58

1 Answers1

0

You can use guard macros, to avoid multiple definitions but this will work only if you have only one translation unit:

header A:

#ifndef HEADERA_H
#define HEADERA_H
// HeaderA.h
#include <Windows.h>

    struct ProcessInfo
    {
         int ProcID;

         HANDLE Handle;

    };
#endif // HEADERA_H

header B:

#ifndef HEADERB_H
#define HEADERB_H

// Header B starts here
// HeaderB.h
#include "HeaderA.h"
{
    ProcessInfo pi;
    pi.ProcID = 10;


    struct Player
    {
        int health = 0;

        float x, y, z;

        int score = 0;
    };
}
#endif // HEADERB_H

the same for headerC

In modern compilers you can also add directive "#pragma once" to the beginnig of each header.

But if you need to use one global variable in different cpp files (translation units) you can use "static" keyword, if you want each translation unit to have own instance of variable.

static ProcessInfo pi;

Or you want share the value between your translation units you can use extern keyword in header and define variable in one of your cpp files.

#ifndef HEADERB_H
#define HEADERB_H

#include "HeaderA.h"
extern ProcessInfo pi;

#endif // HEADERB_H

unitB.cpp

#include "HeaderB.h"
ProcessInfo pi;
pi.ProcID = 10;
Sandro
  • 2,707
  • 2
  • 20
  • 30