StudentX
StudentX

Reputation: 2323

include header file error: multiple definition

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 ?

Upvotes: 3

Views: 6733

Answers (2)

An updated answer for . With the introduction of inline variables, one no longer needs to worry about the exact translation unit where non-const namespace scoped variables need to be placed. Putting aside the discussion about use of global variables in general, another way to fix the OP in modern C++ is to declare the variables as follows:

inline bool x; // Can add an initializer here too
inline int y;

So long as this is in a header and all TU's see the same exact definition, the implementation will resolve it and make sure those TU's all refer to the exact same unique object.

Upvotes: 0

BЈовић
BЈовић

Reputation: 64223

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;

Upvotes: 3

Related Questions