C++ – include header file error: multiple definition

c

I have a very simple file system in a program.

There is :main.cpp which include worker.h, worker.h and worker.cpp which include worker.h

worker.h has the Header guard and has some variables declared which are required by both main.cpp and worker.cpp and it has some function declarations.

#ifndef __WORKER_H_INCLUDED__
#define __WORKER_H_INCLUDED__

    bool x;
    int y;

    void somefunction( int w, int e );

#endif

Going through some other threads and google results, I understood that the Header guard protects you from multiple inclusions in a single source file, not from multiple source files.

So I can expect linker errors.

My question is

  1. Why there are multiple definition errors for only variables and not for functions ? As far as my understanding goes both of those are only declared and not defined in the header file worker.h

  2. How can I make the a variable available to both main.cpp and worker.cpp without the multiple definition linker error ?

Best Answer

Why there are multiple definition errors for only variables and not for functions ? As far as my understanding goes both of those are only declared and not defined in the header file worker.h

Because you defined the variables. This way they are only declared :

extern bool x;
extern int y;

But you have to define them in a cpp file. :

bool x = true;
int y = 42;