as3rdaccount
as3rdaccount

Reputation: 3941

How to compile multiple .c and .h files in gcc linux?

So I have a source mainClass.c where I have the main defined. I have a header file class1.h and the implementation of all the functions defined in class1.h in class1.c. I have two variables (global) in class1.h named cond and mutex which are being used in class1.c for now and probably in future I will be using it in my mainClass.c as well. Now to compile all the source files to generate one object file I am doing something as follows:

gcc -Wall -pthread -I/home/2008/ariarad/mainClass1 mainClass1.c class1.c -o out

/home/2008/ariarad/mainClass1 is where all my header and source files are at and I am using pthead.h in one of the .c file. Even though I have included it there it complains so I had to include it.

Now when I run the above command the I get the following errors:

class1.c:3:16: error: redefinition of ‘cond’
class1.h:66:16: note: previous definition of ‘cond’ was here
class1.c:4:17: error: redefinition of ‘mutex’
class1.h:67:17: note: previous definition of ‘mutex’ was here

Just in case I have an ifndef and endif block surrounding the class1.h to avoid multiple inclusion. I am definitely not redefining the variables defined in the header file in the .c file. So can someone please help me why it is still giving me the errors?

Upvotes: 5

Views: 4986

Answers (1)

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

You cannot define global variables in header files. You must define them in one of the .c files, and then use extern in the header files:

In one of the .c files:

int cond;

In one of the .h files, which must be included by all .c files that need the variable:

extern int cond;

Upvotes: 7

Related Questions