Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
363 views
Welcome To Ask or Share your Answers For Others

1 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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...