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

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

c++ - 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 ?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...