2

I have a variable that I intend to use in multiple files, is a mutex initializer.

So I wrote in one header file this :

#ifndef LISTEN_H_
#define LISTEN_H_

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

#endif

I tried to include the header in the files in witch I intend to use the variable.

But i get : error mutex has already been declared here.

What is the proper way to use a global variable in multiple header files ?

1 Answer 1

6

The proper way would be to define it in a .c file and declare it as extern in the header file. Now you would be able to use it wherever you want to use it, without errors.

Sign up to request clarification or add additional context in comments.

4 Comments

then whats the purpose of header guard..?
@Mr.32 the include guard prevents the file from being included multiple times IN THE SAME translation unit - i.e during compilation.
@Mr.32 This error, is due to multiple copies of the variables defined in different translation units - during linking stage.
@KarthikT oh OP hasnt specify that in question still u get it..great +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.